/* RUNNING : LIVE DEV */ var _ui_share_app = angular.module('uiShareMaster', []); var _ui_share_host = 'extensions/devsource/dev.sugarfree/share/'; /* Component Config */ _ui_share_app.config(function ($routeProvider, $locationProvider, $httpProvider, $sceProvider) { $httpProvider.defaults.useXDomain = true; $httpProvider.defaults.withCredentials = true; delete $httpProvider.defaults.headers.common["X-Requested-With"]; }); /* Component Factory/Service */ _ui_pvt_m.service('thirdPartyRun', function () { this.jquery_ = function () { if (typeof jQuery === 'uindefined' || typeof $ === 'undefined') { console.log("jQuery is not loaded"); } }; this.slick_ = function () { if (!jQuery().slick || typeof jQuery().slick === 'undefined') { /*console.log("Slick is not loaded");*/ } }; this.fancybox_ = function () { if (!jQuery().fancybox || typeof jQuery().fancybox === 'undefined') { /*console.log("Fancybox is not loaded");*/ } }; this.store_ = function(){ if(typeof store == undefined){ } }; this.run = function () { this.jquery_(); this.slick_(); /*this.fancybox_();*/ }; }); _ui_pvt_m.service('shopStoreData', function () { this.data = false; this.set = function (getData) { this.data = getData; }; }); _ui_pvt_m.directive("isImageLoad", function () { return { restrict: "A", link: function (scope, element, attrs) { element.bind('load', function () { element.addClass('image_lazy_loaded'); }); } }; }); _ui_pvt_m.directive('compile', function ($compile) { return function (scope, element, attrs) { scope.$watch( function (scope) { return scope.$eval(attrs.compile); }, function (value) { element.html(value); $compile(element.contents())(scope); } ); }; }); _ui_share_app.service('carouselData', function () { this.data = { main: false, secondary: false, mainbanner: false, topbanner: false, bottombanner: false, minibanner: false }; this.set = function (type, inputData) { if (typeof inputData !== 'undefined') { switch (type) { case 'carouselMain': this.data.main = inputData; break; case 'carouselSecondary': this.data.secondary = inputData; break; case 'mainBanner': this.data.mainbanner = inputData; break; case 'topBanner': this.data.topbanner = inputData; break; case 'bottomBanner': this.data.bottombanner = inputData; break; case 'miniBanner': this.data.minibanner = inputData; break; } } }; this.fetch = function (type) { switch (type) { case 'carouselMain': return this.data.main || false; break; case 'carouselSecondary': return this.data.secondary || false; break; case 'mainBanner': return this.data.mainbanner || false; break; case 'topBanner': return this.data.topbanner || false; break; case 'bottomBanner': return this.data.bottombanner || false; break; case 'miniBanner': return this.data.minibanner || false; break; default: return false; break; } }; this.get = function (type) { return this.fetch(type); }; }); _ui_share_app.directive('repeatEnd', ['$rootScope', function ($rootScope) { return { restrict: 'A', link: function (scope) { if (scope.$last) { $rootScope.$broadcast('repeatend'); } } }; }]); function ISMOBILE() { var Uagent = navigator.userAgent||navigator.vendor||window.opera; return(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino|android|ipad|playbook|silk/i.test(Uagent)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(Uagent.substr(0,4))); }; _ui_share_app.factory('$fallback', function ($routeParams,$route,$location) { var promise = { init: function(){ var $shopId = parseInt(CUR_THEME.shop_id()); var $page = (typeof $route.current.$$route.page !== 'undefined') ? $route.current.$$route.page : false; if(!$page){ return $location.path('/home'); } this.checkParams($shopId,$page); }, checkParams: function(shopId, currentPage){ switch(shopId){ case 549: /* Happylife */ if(currentPage === 'category-lists'){ if(!$routeParams.referral_id || !$routeParams.root_id || !$routeParams.referral_type){ $location.path('/home'); } } break; } /* Common Fallback: Product Detail */ if(currentPage === 'product-detail'){ if($routeParams.product_id == 0 || !$routeParams.product_id){ $location.path('/home'); } } /* Common Fallback: Blog Detail */ if(currentPage === 'blog-detail'){ if($routeParams.blog_id == 0 || !$routeParams.blog_id){ $location.path('/home'); } } } }; return promise; });/* FOR : MISSMONRIBS (first page) */ _ui_share_app.directive('cardProductA', function($rootScope, $routeParams) { var templateName = 'cardProductA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '=productdata', noanimate: '@noanimate', to: '@to', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.item = $scope.productdata; $scope.use_no_animate = (typeof $scope.noanimate !== 'undefined' && $scope.noanimate == 'true') ? true : false; $scope._to = (typeof $scope.to !== 'undefined') ? $scope.to : 'null'; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.exceptVisibleBadge = function(objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: s = true; break; default: s = false; break; } return s; }; $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { /* case 16: str = "FEATURED"; break; */ case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; } return str; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.viewProduct = function(id) { window.$componentBuyButtonAttribute.unActive(); $timeout(function() { window.$componentBuyButtonAttribute.active(id); }, 100); }; $scope.consoleLog = function(status, data = '') { var statuslog = false; if (statuslog) { console.log(status, data); } }; $scope.checkProcess = function(id) { return (UiCart.delegate.product.isProgress(id)) ? true : false; }; /* check if product added */ $scope.statusPopUp = false; $scope.checkAdded = function(id) { /*return (UiCart.delegate.product.isSelected(id)) ? true : false;*/ var productid = (UiCart.delegate.product.isSelected(id)) ? true : false; if (productid == true) { var attribute = $('[data-id="attribute_of_' + id + '"]'); if (!attribute.hasClass('open')) { $scope.product_id = ''; $scope.product_price = ''; $scope.selectedOptionTextJson = ''; $scope.lastCheckedVariantKey = ''; $scope.productOptionLevelArray = []; $scope.optionToCalculateNext = false; $scope.optionNotFound = 0; $scope.check_alloption = false; $scope.buy_button = false; } } return productid; }; $scope.onPress = function(id, qty, attribute = 0, total) { $scope.doAnimateStart(id, qty, attribute, total); }; $scope.doAnimateStart = function(id, qty, attribute, total) { return $scope.buyProcess(id, qty, attribute, total); } $scope.textPopUp = ''; $scope.buyProcess = function(product_id, quantity, attribute, total) { console.log("buyProcess", product_id, quantity); $scope.consoleLog("buyProcess", product_id); if (!UiCart.delegate.product.isSelected(product_id)) { $scope.consoleLog("buyProcess 1 if", product_id); if (!UiCart.delegate.product.isProgress(product_id)) { $scope.consoleLog("buyProcess 2 if", product_id); $scope.consoleLog("buyProcess 2 attribute", attribute); if (attribute.length == 0 || attribute.option_data.variant_array <= 1) { $scope.textPopUp = "เข้าตะกร้าเรียบร้อยแล้ว"; $scope.popUpopen(product_id); $scope.popUpcloseAuto(product_id); $scope.consoleLog("buyProcess 2.1 if not attribute", attribute); UiCart.delegate.product.add(product_id, quantity, function(output) { $scope.consoleLog("buyProcess 3 UiCart.delegate.product.add output : ", output); if (output !== false) { $scope.consoleLog("buyProcesds 4 if output : ", output); if (!$('#root-virtual-cart-type-a').hasClass('is-open') && $(window).width() > 767) { $virtualCartTypeA.isOpenOrClose(); } else { $virtualCartTypeA.load(); } } else { $scope.consoleLog("buyProcess 4 else output : ", output); } }); } else { $scope.resetData(); $scope.statusPopUp = true; $scope.consoleLog("buyProcess 2.1 else attribute", attribute); var attribute = $('[data-id="attribute_of_' + product_id + '"]'); attribute.addClass('open'); } } else { $scope.consoleLog("buyProcess 2 else", product_id); } } else { $scope.consoleLog("buyProcess 1 else", product_id); } }; $scope.product_id = ''; $scope.product_price = ''; $scope.selectedOptionTextJson = ''; $scope.lastCheckedVariantKey = ''; $scope.productOptionLevelArray = []; $scope.optionToCalculateNext = false; $scope.optionNotFound = 0; $scope.check_alloption = false; $scope.buy_button = false; $scope.resetData = function() { $scope.product_id = ''; $scope.product_price = ''; $scope.selectedOptionTextJson = ''; $scope.lastCheckedVariantKey = ''; $scope.productOptionLevelArray = []; $scope.optionToCalculateNext = false; $scope.optionNotFound = 0; $scope.check_alloption = false; $scope.buy_button = false; } $scope.chageProductOptionId = function($event, masterIndex, optionId, product_attribute) { $scope.consoleLog("chageProductOptionId event", $event); $scope.consoleLog("chageProductOptionId masterIndex", masterIndex); $scope.consoleLog("chageProductOptionId optionId", optionId); function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } $scope.productOptionLevelArray[masterIndex] = optionId; $scope.consoleLog("chageProductOptionId clicked optionId ", $scope.productOptionLevelArray); var optionSelectedArray = []; for (var i = 0; i < $scope.productOptionLevelArray.length; i++) { if ($scope.productOptionLevelArray[i] != 0) { optionSelectedArray.push($scope.productOptionLevelArray[i]); } } if (optionSelectedArray.length === product_attribute.option_data.pclass_array.length) { $scope.optionToCalculateNext = true; } if (!$scope.optionToCalculateNext) { $scope.consoleLog("chageProductOptionId : Failed ", $scope.optionToCalculateNext); $scope.consoleLog("chageProductOptionId : Failed Data optionSelectedArray Length ", optionSelectedArray.length); $scope.consoleLog("chageProductOptionId : Failed Data pclass_array Length ", product_attribute.option_data.pclass_array.length); $scope.consoleLog("chageProductOptionId : Failed Data optionSelectedArray ", optionSelectedArray); $scope.consoleLog("chageProductOptionId : Failed Data pclass_array ", product_attribute.option_data.pclass_array); return; } $scope.optionNotFound = 0; for (var i = 0; i < product_attribute.option_data.variant_array.length; i++) { var _self = product_attribute.option_data.variant_array[i]; var _self_option = angular.fromJson(_self.option_id_json); if (compareArray(optionSelectedArray, _self_option)) { $scope.product_id = _self.product_id; $scope.product_price = _self.price; $scope.consoleLog("chageProductOptionId : selectedOptionTextJson: option ", _self); $scope.check_alloption = true; $scope.buy_button = true; $scope.selectedOptionTextJson = _self.option_id_json; console.log('selectedOptionTextJson: Key', '-' + optionSelectedArray.join('-') + '-'); $scope.switchQuantityByKey('-' + optionSelectedArray.join('-') + '-'); if (_self.variant_image.length) { var rightImagePosition = 0; } $scope.optionNotFound = 0; break; } else { $scope.optionNotFound++; $scope.check_alloption = false; $scope.buy_button = false; } } $scope.consoleLog("chageProductOptionId : optionNotFound ", $scope.optionNotFound); $scope.consoleLog("chageProductOptionId : pclass_array Length ", product_attribute.option_data.pclass_array.length); } $scope.switchQuantityByKey = function(variant_key) { $scope.lastCheckedVariantKey = variant_key; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price[variant-key!="' + variant_key + '"]').removeClass('active').removeClass('inin'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('active'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('active'); $timeout(function() { $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('inin'); }, 300); }; $scope.close = function(product_id) { $scope.statusPopUp = false; var attribute = $('[data-id="attribute_of_' + product_id + '"]'); attribute.removeClass('open'); } $scope.popUpopen = function(product_id) { $scope.statusPopUp = true; var attribute = $('[data-id="attribute_of_popup_' + product_id + '"]'); attribute.addClass('open'); } $scope.popUpopenAuto = function(product_id) { $scope.textPopUp = "เข้าตะกร้าเรียบร้อยแล้ว"; var attribute = $('[data-id="attribute_of_popup_' + product_id + '"]'); attribute.addClass('open'); $scope.popUpcloseAuto(product_id); } $scope.popUpclose = function(product_id) { $scope.statusPopUp = false; var attribute = $('[data-id="attribute_of_popup_' + product_id + '"]'); attribute.removeClass('open'); } $scope.popUpcloseAuto = function(product_id) { setTimeout(function() { var attribute = $('[data-id="attribute_of_popup_' + product_id + '"]'); attribute.removeClass('open'); }, 2500); } }; return promise; });/* FOR ZoomCamera (v1 cart) : design 1 */ _ui_share_app.directive('cardProductB', function ($rootScope, $routeParams) { var templateName = 'cardProductB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata:'=productdata', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); /* FOR ZoomCamera (v1 cart) : design 2 */ _ui_share_app.directive('cardProductC', function ($rootScope, $routeParams) { var templateName = 'cardProductC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata:'=productdata', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); /* FOR myhappyphone component (component-grid-category-g) *//* FOR ZoomCamera (v2) (with component-page-type-na) */ _ui_share_app.directive('cardProductE', function ($rootScope, $routeParams) { var templateName = 'cardProductE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '=productdata', productall: '@productall', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function (objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function (objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function () { return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function (expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Build title for Address link*/ $scope.buildTitleUrl = function (str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* $scope.handleChange = function(checkbox) { if(checkbox.checked == true){ document.getElementById(checkbox).removeAttribute("disabled"); }else{ document.getElementById(checkbox).setAttribute("disabled", "disabled"); } };*/ $scope.invited = []; $scope.isChecked = []; $scope.insertinvited = function (user) { if ($scope.isChecked[user]) { $scope.invited.push(user); console.log("test_array :", $scope.invited); } else { var toDel = $scope.invited.indexOf($scope.productall); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } } $scope.displayImage = function (image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.addProductTocart = function(product_id){ UiCart.delegate.product.add(product_id, 1); }; $scope.checkAdded = function (id) { return (UiCart.delegate.product.isSelected(id)) ? true : false; }; }; return promise; });/* FOR ZoomCamera (v2) (with component-page-type-na) */ _ui_share_app.directive('cardProductEa', function ($rootScope, $routeParams) { var templateName = 'cardProductEa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '=productdata', productall: '@productall', datafont: '@datafont', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function (objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function (objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function () { return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function (expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Build title for Address link*/ $scope.buildTitleUrl = function (str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* $scope.handleChange = function(checkbox) { if(checkbox.checked == true){ document.getElementById(checkbox).removeAttribute("disabled"); }else{ document.getElementById(checkbox).setAttribute("disabled", "disabled"); } };*/ $scope.invited = []; $scope.isChecked = []; $scope.insertinvited = function (user) { if ($scope.isChecked[user]) { $scope.invited.push(user); console.log("test_array :", $scope.invited); } else { var toDel = $scope.invited.indexOf($scope.productall); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } } $scope.displayImage = function (image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.addProductTocart = function(product_id){ UiCart.delegate.product.add(product_id, 1); }; $scope.checkAdded = function (id) { return (UiCart.delegate.product.isSelected(id)) ? true : false; }; }; return promise; });/* (myhappyphone product card) product card for *//* FOR lightmax (v1) */ _ui_share_app.directive('cardProductG', function ($rootScope, $routeParams) { var templateName = 'cardProductG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata:'=productdata', viewdata:'=viewdata', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Build title for Address link*/ $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); /* FOR lightmax (v1) */ _ui_share_app.directive('cardProductH', function ($rootScope, $routeParams) { var templateName = 'cardProductH'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata:'=productdata', indexdata:'=indexdata', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; console.log("dat_product_set",$scope.item); /* console.log("dat_product_set_image",$scope.item.product_image[0].image_url);*/ /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); }else { return ''; } } /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Build title for Address link*/ $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); /* FOR ZoomCamera (category list) */ _ui_share_app.directive('cardProductI', function($rootScope, $routeParams) { var templateName = 'cardProductI'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '=productdata', viewType: '@view', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.item = $scope.productdata; /* Hide when visible badge */ if ($scope.stylebutton == "") { $scope.stylebutton = "special_filled_button_small_round"; } $scope.exceptVisibleBadge = function(objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Build title for Address link*/ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; }; return promise; });/* FOR ZoomCamera (category list) */ _ui_share_app.directive('cardProductIa', function($rootScope, $routeParams) { var templateName = 'cardProductIa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '=productdata', viewType: '@view', stylebutton: '@stylebutton', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.item = $scope.productdata; /* Hide when visible badge */ if ($scope.stylebutton == "") { $scope.stylebutton = "special_filled_button_small_round"; } $scope.exceptVisibleBadge = function(objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Build title for Address link*/ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; }; return promise; });/* FOR : MISSMONRIBS (first page) */ _ui_share_app.directive('cardProductK', function ($rootScope, $routeParams) { var templateName = 'cardProductK'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata:'=productdata', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* Optimize image size by device pixel * @params {size} (integer) prefer size * @params {image_url} (string) original image source link * @params {image_width} (string) original image width * @return string */ $scope.viewOptimizeImage = function(size, image_url, image_width){ if(window.devicePixelRatio >= 2 || parseInt(image_width) <= size){ return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't'+size+'_' + b; return a.join("/"); }; }; return promise; }); /* FOR zoomcamera (detail page (relate product)) */ _ui_share_app.directive('cardProductL', function ($rootScope, $routeParams) { var templateName = 'cardProductL'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata:'=productdata', viewdata:'=viewdata', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Build title for Address link*/ $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* Optimize image size by device pixel * @params {size} (integer) prefer size * @params {image_url} (string) original image source link * @params {image_width} (string) original image width * @return string */ $scope.viewOptimizeImage = function(size, image_url, image_width){ if(window.devicePixelRatio >= 2 || parseInt(image_width) <= size){ return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't'+size+'_' + b; return a.join("/"); }; }; return promise; }); /* FOR ZoomCamera (v1 cart) : design 1 */ _ui_share_app.directive('cardProductM', function ($rootScope, $routeParams) { var templateName = 'cardProductM'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata:'=productdata', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); /* FOR ZoomCamera (v1 cart) : design 1 */ _ui_share_app.directive('cardProductN', function ($rootScope, $routeParams) { var templateName = 'cardProductN'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata:'=productdata', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Display Badge Name (all) */ $scope.dispalyBadgeText = function(objectItem,stringCheck){ var badgeNameArray = []; var badgeNameRender = function(id){ var str = 'No'; switch(id){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; for(var i = 0; i < objectItem.length; i++){ badgeNameArray.push(badgeNameRender(parseInt(objectItem[i].badge_id))); } return (badgeNameArray.indexOf(stringCheck) !== -1) ? true : false; }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s.toLowerCase(); }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; }; return promise; }); /* FOR ZoomCamera (v1 cart) : design 1 */ _ui_share_app.directive('cardProductO', function ($rootScope, $routeParams) { var templateName = 'cardProductO'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name:'@name', productdata:'=productdata', imgpath: '@imgpath', imgcart: '@imgcart', carousel: '@carousel', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); /* FOR ZoomCamera (category list) */ _ui_share_app.directive('cardProductP', function($rootScope, $routeParams) { var templateName = 'cardProductP'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '=productdata', viewType: '@view', stylebutton: '@stylebutton', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.item = $scope.productdata; /* Hide when visible badge */ if ($scope.stylebutton == "") { $scope.stylebutton = "special_filled_button_small_round"; } $scope.exceptVisibleBadge = function(objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem) { /* var r = objectItem;*/ var str = 'No Badge'; for (var i = 0;i< objectItem.length; i++) { switch (parseInt(objectItem[i].badge_id)) { /* case 16: str = "FEATURED"; break;*/ case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; /* case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break;*/ } } console.log("oiereorie :", str); return str; }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Build title for Address link*/ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; }; return promise; });/* FOR ZoomCamera (v1 cart) : design 1 */ _ui_share_app.directive('cardProductQ', function ($rootScope, $routeParams) { var templateName = 'cardProductQ'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata:'=productdata', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); /* FOR ZoomCamera (v2) (with component-page-type-na) */ _ui_share_app.directive('cardProductR', function ($rootScope, $routeParams) { var templateName = 'cardProductR'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '=productdata', productall: '@productall', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; /* Hide when visible badge */ $scope.exceptVisibleBadge = function (objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function (objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function () { return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function (expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Build title for Address link*/ $scope.buildTitleUrl = function (str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* $scope.handleChange = function(checkbox) { if(checkbox.checked == true){ document.getElementById(checkbox).removeAttribute("disabled"); }else{ document.getElementById(checkbox).setAttribute("disabled", "disabled"); } };*/ $scope.invited = []; $scope.isChecked = []; $scope.insertinvited = function (user) { if ($scope.isChecked[user]) { $scope.invited.push(user); console.log("test_array :", $scope.invited); } else { var toDel = $scope.invited.indexOf($scope.productall); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } } $scope.displayImage = function (image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.addProductTocart = function(product_id){ UiCart.delegate.product.add(product_id, 1); }; $scope.checkAdded = function (id) { return (UiCart.delegate.product.isSelected(id)) ? true : false; }; }; return promise; });/* FOR ZoomCamera (v2) (with component-page-type-na) */ _ui_share_app.directive('cardProductWa', function($rootScope, $routeParams) { var templateName = 'cardProductWa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '=productdata', productall: '@productall', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* Hide when visible badge */ $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope.data = false; $scope.product_original_id = $scope.item.product_id; $scope.getData = function(id) { var d = { 'txt_product_id': id }; GAEAPI.get('product/id', d, $scope).then(function(res) { var e = res.data; console.log("efjkdfjkdfjdfjdfjdfkd : ", res); if (res.ok == 1) { $scope.data = res.data; $scope._dataArray = res.data; /*$scope.buildMultipleQuantity(e.data);*/ if (res.data.product_attribute.length != 0) { if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { // alert("x๊อบไข่สด"); var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ", $scope.data_min); $scope.buildVariantOption(res.data); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } $scope.qtyCurrentSize(res.data.product_total_variant, res.data.product_total_stock); } }); }; $scope.getData($scope.item.product_id); $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); // console.log("Askdjkdhfsjfhdjfhdjfhdj : ",optionJson[0]); console.log("dataVariants :", dataVariants); var count = 0; if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.qtyCurrentSize = function(product_total_variant, product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : product_total_variant : ", product_total_variant, "product_total_stock : ", product_total_stock); if (product_total_variant == 0) { if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < parseInt(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock < 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock == 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else { $scope.qty_current_size_state = false; $scope.buy_state = false; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_variant > 0) { if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < product_total_stock; i++) { $scope.qty_current_size.push(i + 1); } } } $scope.qtyShow($scope.qty_current_size); }; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope.exceptVisibleBadge = function(objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Build title for Address link*/ /* $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; */ /* $scope.handleChange = function(checkbox) { if(checkbox.checked == true){ document.getElementById(checkbox).removeAttribute("disabled"); }else{ document.getElementById(checkbox).setAttribute("disabled", "disabled"); } };*/ $scope.invited = []; $scope.isChecked = []; $scope.insertinvited = function(user) { if ($scope.isChecked[user]) { $scope.invited.push(user); console.log("test_array :", $scope.invited); } else { var toDel = $scope.invited.indexOf($scope.productall); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } } $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.addProductTocart = function(product_id) { UiCart.delegate.product.add(product_id, 1); }; $scope.redirectCheckout = function(p, q) { window.location.href = GURL.base_url() + "checkout?pdata=" + p + '-' + q; }; $scope.checkAdded = function(id) { return (UiCart.delegate.product.isSelected(id)) ? true : false; }; $scope.check_id = function(text_number) { var optionJson = angular.fromJson(text_number); return optionJson[0]; }; }; return promise; });/* FOR ZoomCamera (v2) (with component-page-type-na) */ _ui_share_app.directive('cardProductWb', function ($rootScope, $routeParams) { var templateName = 'cardProductWb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '=productdata', productall: '@productall', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.item = $scope.productdata; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* Hide when visible badge */ $scope.exceptVisibleBadge = function (objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 18: case 19: case 71: case 81: case 82: case 83: case 84: s = true; break; default: s = false; break; } return s; }; /* Display Badge Name */ $scope.renderBadgeType = function (objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; /* Check if seo enable */ $scope.checkSeo = function () { return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function (expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Build title for Address link*/ $scope.buildTitleUrl = function (str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* $scope.handleChange = function(checkbox) { if(checkbox.checked == true){ document.getElementById(checkbox).removeAttribute("disabled"); }else{ document.getElementById(checkbox).setAttribute("disabled", "disabled"); } };*/ $scope.invited = []; $scope.isChecked = []; $scope.insertinvited = function (user) { if ($scope.isChecked[user]) { $scope.invited.push(user); console.log("test_array :", $scope.invited); } else { var toDel = $scope.invited.indexOf($scope.productall); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } } $scope.displayImage = function (image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.addProductTocart = function(product_id){ UiCart.delegate.product.add(product_id, 1); }; $scope.redirectCheckout = function(p,q){ window.location.href = GURL.base_url() + "checkout?pdata="+p+'-'+q; }; $scope.checkAdded = function (id) { return (UiCart.delegate.product.isSelected(id)) ? true : false; }; }; return promise; });_ui_share_app.directive('categoryPageTypeMaeju', function($rootScope, $routeParams, $location) { var templateName = 'categoryPageTypeMaeju'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { limit: '@limit', category: '@category', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { /* console.log('categoryPageTypeMaeju : ', name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = "สินค้า"; $scope.sub_products = "0"; $scope.state = ""; $scope.dataArray6113 = []; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.category; $scope.state = "main_category"; $scope.dataRelationState = $scope.getData().stateData(false, true); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.category; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.category; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; if (output.data == 0) { $scope.state = "sub_category_products"; $scope.sub_products = params.referral_id; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.sub_products = params.sendtag; var dataSend = { 'txt_referral_id': 6113 }; $scope.getData().dataSend('referral/id_map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray6113 = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "สินค้าใหม่"; } else if (params.badge_id == "74") { $scope.cover_top = "สินค้าขายดี"; } else if (params.badge_id == "75") { $scope.cover_top = "สินค้าแนะนำ"; } $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.categoriesData = $scope.routeParams().referral_id || ''; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; if (typeof $scope.sortData != 'undefined' && $scope.sortData !== "") { page += '&sort=' + $scope.sortData; } else { delete $scope.sortData; } if (typeof $scope.badgeData != 'undefined' && $scope.badgeData !== "") { page += '&badge=' + $scope.badgeData; } else { delete $scope.badgeData; } } else { delete $scope.categoriesDat; delete $scope.sortData; delete $scope.badgeData; } $location.url(page).replace(); }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().badge || ''; $scope.setReferralIdMapData = function(input) { $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } else { if (typeof data.sort != 'undefined' && data.sort !== "") { page += '?sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('categoryPageTypeStyle', function($rootScope, $routeParams, $location) { var templateName = 'categoryPageTypeStyle'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', limit: '@limit', category: '@category', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { /* console.log('categoryPageTypeStyle : ', name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = "สินค้า"; $scope.sub_products = "0"; $scope.state = ""; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.category; $scope.state = "main_category"; $scope.dataRelationState = $scope.getData().stateData(false, true); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.category; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.category; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; if (output.data == 0) { $scope.state = "sub_category_products"; $scope.sub_products = params.referral_id; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "สินค้าใหม่"; } else if (params.badge_id == "74") { $scope.cover_top = "สินค้าขายดี"; } else if (params.badge_id == "75") { $scope.cover_top = "สินค้าแนะนำ"; } $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.categoriesData = $scope.routeParams().referral_id || ''; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; if (typeof $scope.sortData != 'undefined' && $scope.sortData !== "") { page += '&sort=' + $scope.sortData; } else { delete $scope.sortData; } if (typeof $scope.badgeData != 'undefined' && $scope.badgeData !== "") { page += '&badge=' + $scope.badgeData; } else { delete $scope.badgeData; } } else { delete $scope.categoriesDat; delete $scope.sortData; delete $scope.badgeData; } $location.url(page).replace(); }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().badge || ''; $scope.setReferralIdMapData = function(input) { $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } else { if (typeof data.sort != 'undefined' && data.sort !== "") { page += '?sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('comingSoonPage', function($rootScope, $routeParams) { var templateName = 'comingSoonPage'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', typecoming: '@typecoming', imgpath: '@imgpath', logo: '@logo', enable: '@enable', key: '@key' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'bottom_one': '?bottomOne', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.txt_key = ''; $scope._typecoming = (typeof $scope.typecoming !== 'undefined' && $scope.typecoming !== '') ? $scope.typecoming : 'null'; $('body').css('overflow', 'hidden'); $scope.showInputKey = function() { angular.element(".container-key .close").hide(); angular.element(".container-key .box").show(); }; $scope.$watch('txt_key', function(newValue, oldValue) { if (!newValue || newValue == "") { return; } if (newValue == $scope.key) { $('body').css('overflow', 'auto'); angular.element(".key-lock").hide(); } }); }; return promise; });_ui_share_app.directive('comingSoonPageTypeA', function($rootScope, $routeParams) { var templateName = 'comingSoonPageTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { backgroundcolor: '@backgroundcolor', color: '@color', height: '@height', width: '@width', text: '@text', icon: '@icon', nclick: '@nclick', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'bottom_one': '?bottomOne', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._text = (typeof $scope.text !== 'undefined' && typeof $scope.text !== '') ? ($scope.text == 'false') ? false : ($scope.text == 'true') ? true : true : true; $scope._icon = (typeof $scope.icon !== 'undefined' && typeof $scope.icon !== '') ? $scope.icon : ''; $scope._nclick = (typeof $scope.nclick !== 'undefined' && typeof $scope.nclick !== '') ? $scope.nclick : ''; $scope.showInputKey = function() { $('.key-lock').hide(); $('body').css('overflow', 'auto'); } $scope.show = function() { $('body').css('overflow', 'hidden'); } $scope.show(); }; return promise; });_ui_share_app.directive('comingSoonPageTypeB', function($rootScope, $routeParams) { var templateName = 'comingSoonPageTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { backgroundcolor: '@backgroundcolor', color: '@color', height: '@height', width: '@width', text: '@text', icon: '@icon', nclick: '@nclick', key: '@key', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'bottom_one': '?bottomOne', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.txt_key = ''; $scope._text = (typeof $scope.text !== 'undefined' && typeof $scope.text !== '') ? ($scope.text == 'false') ? false : ($scope.text == 'true') ? true : true : true; $scope._icon = (typeof $scope.icon !== 'undefined' && typeof $scope.icon !== '') ? $scope.icon : ''; $scope._nclick = (typeof $scope.nclick !== 'undefined' && typeof $scope.nclick !== '') ? $scope.nclick : ''; $scope.showInputKey = function() { $('.key-lock').hide(); $('body').css('overflow', 'auto'); } $scope.show = function() { $('body').css('overflow', 'hidden'); } $scope.show(); $scope.$watch('txt_key', function(newValue, oldValue) { if (!newValue || newValue == "") { return; } if (newValue == $scope.key) { $scope.showInputKey(); } }); }; return promise; });_ui_share_app.directive('comingSoonPageTypeC', function($rootScope, $routeParams) { var templateName = 'comingSoonPageTypeC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'cover_img': '?coverImg', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.showInputKey = function() { $('body').css('overflow', 'auto'); $('.cover_lock_key').hide(); } $scope.show = function() { $('body').css('overflow', 'hidden'); } $scope.show(); }; return promise; });_ui_share_app.factory('$componentAbout', function componentAbout($routeParams, $timeout) { return });_ui_share_app.directive('componentAboutA', function($rootScope, $routeParams) { var is_componentAboutA_start = false; var templateName = 'componentAboutA'; var componentMain = 'componentAbout'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.about = false; $scope.getShopCurrentAboutus = function() { GAEAPI.get('shop/current', {}, $scope).then(function(e) { if (e.ok == 1) { $scope.about = GAEAPI.getValue(e.data, {}); } }); }; $scope.getShopCurrentAboutus(); }; return promise; });_ui_share_app.directive('componentAboutB', function($rootScope, $routeParams) { var is_componentAboutA_start = false; var templateName = 'componentAboutB'; var componentMain = 'componentAbout'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.about = false; $scope.getShopCurrentAboutus = function() { GAEAPI.get('shop/current', {}, $scope).then(function(e) { if (e.ok == 1) { $scope.about = GAEAPI.getValue(e.data, {}); } }); }; $scope.getShopCurrentAboutus(); }; return promise; });_ui_share_app.directive('componentAboutC', function($rootScope, $routeParams) { var is_componentAboutA_start = false; var templateName = 'componentAboutC'; var componentMain = 'componentAbout'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.getShopCurrentAboutus = function() { $scope._dataArrayState = $scope.StateData(true, false); GAEAPI.get('shop/current', {}, $scope).then(function(e) { if (e.ok == 1) { $scope._dataArray = e.data; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getShopCurrentAboutus(); }; return promise; });_ui_share_app.directive('componentAboutCode', function ($rootScope) { var templateName = 'componentAboutCode'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', code:'@code', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'about_headline':'?aboutHeadline', 'about_textleft':'?aboutTextleft', 'about_description':'?aboutDescription', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; }; return promise; }); _ui_share_app.directive('componentAboutPage', function ($rootScope, $routeParams) { var templateName = 'componentAboutPage'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.factory('$componentAccess', function componentAccess($routeParams, $timeout) { return });_ui_share_app.directive('componentAccessOneColumnTypeA', function($rootScope, $routeParams) { var templateName = 'componentAccessOneColumnTypeA'; var componentMain = 'componentAccess'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { col: '@col', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'show_one': '?showOne', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; }; return promise; });_ui_share_app.directive('componentAccessTwoColumn', function($rootScope, $routeParams) { var templateName = 'componentAccessTwoColumn'; var componentMain = 'componentAccess'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'show_left': '?showLeft', 'show_right': '?showRight', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; }; return promise; });_ui_share_app.directive('componentAccessFromForgotPassword', function($rootScope, $routeParams) { var componentMain = 'componentAccess'; var componentChild = 'fromforgotpassword'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', domain: '@domain', facebookid: '@facebookid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { /* Variable */ $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.success = false; $scope.loading = false; $scope.rememberMe = false; $scope.member = [{ input: "", name: "อีเมล Email", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkFormat", format: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, statusError: null, error: "ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)" }]; /* Variable */ /* Modify */ $scope.modify = function() { var modify = { checkFormat: function(index) { if ($scope.member[index].type == "password") { $scope.member[index].type = "text"; } else { $scope.member[index].type = "password"; } } }; return modify; }; /* Modify */ /* Format */ $scope.format = function() { var format = { checkFormat: function(format, input, callback) { var format_email = format; var output_check = format_email.test(input); var status_check = false; if (output_check) { status_check = true; } callback(status_check); }, checkLength: function(formatLength, input, callback) { var status_check = false; if (input.length > formatLength) { status_check = true; } callback(status_check); } }; return format; }; /* Format */ /* api */ $scope.api = function() { var api = { checkEmail: function(input, callback) { var dataSend = { txt_email: input }; GAEAPI.post('customer/is_exists_email', dataSend, $scope).then(function(output) { console.log("checkEmail : output : ", output); if (output.ok == 0) { callback(true) } else { callback(false) } }); }, checkOk: function(data, callback) { var check_ok = false; if (data.ok == 1) { check_ok = true; } callback(check_ok); }, customerForgotPassword: function(email, callback) { var dataSend = { 'txt_email': email }; GAEAPI.post('customer/forgot_password', dataSend, $scope).then(function(output) { $scope.api().checkOk(output, function(check_ok) { callback(check_ok) }); }); } }; return api; }; /* api */ /* Submit */ $scope.submitCallApi = function() { $scope.api().checkEmail($scope.member[0].input, function(resultCheck) { console.log("checkEmail : resultCheck : ", resultCheck); if (resultCheck) { $scope.loading = true; $scope.api().customerForgotPassword($scope.member[0].input, function(check_ok) { console.log("submitCallApi : customerForgotPassword : check_ok : ", check_ok); if (check_ok) { setTimeout(function() { $scope.loading = false; $scope.success = true; }, 100); } else { alert("ขออภัย! พบข้อผิดพลาดในการติดต่อระบบ"); $scope.loading = false; } }); } else { for (var i = 0; i < $scope.member.length; i++) { console.log("checkEmail : statusError : ", $scope.member[i].statusError); $scope.member[i].statusError = resultCheck; } } }); }; $scope.submit = function() { for (var i = 0; i < $scope.member.length; i++) { console.log("submit : ", $scope.member[i].name, " : input : ", $scope.member[i].input); if ($scope.member[i].typeFormat == "checkFormat") { $scope.format().checkFormat($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } else if ($scope.member[i].typeFormat == "checkLength") { $scope.format().checkLength($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } } for (var i = 0; i < $scope.member.length; i++) { if (!$scope.member[i].statusError) { return; } } $scope.submitCallApi(); }; /* Submit */ /* page view */ $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.viewPage = function(page) { $scope.viewRouteParams().view = page; }; $scope.windowLocationHref = function(page) { window.location.href = page; }; /* page view */ }; return promise; });_ui_share_app.directive('componentAccessFromForgotPasswordTypeA', function($rootScope, $routeParams) { var componentMain = 'componentAccess'; var componentChild = 'fromforgotpasswordtypea'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.forgotpassword = { email: '', }; $scope.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', }; /* validateLogin */ $scope.validateForgotpassword = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $scope.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $scope.error.email = false; $scope.error.emailExist = false; $('#forgotpassword-email').css('border', ''); }, email: function() { var v = $('#component-access-from-forgot-password-type-a-email').val(); var t = this; if (v.length <= 0) { $scope.validateForgotpassword().emailInputNullError(); $scope.error_email = false; $scope.error_emailExist = false; return false; } else { var valid = $scope.helper.isEmail(v, true); if (v.length > 0 && !valid) { $scope.validateForgotpassword().emailInputError(); $scope.error_email = true; return false; } else if (v.length > 0 && valid) { $scope.validateForgotpassword().emailOk(); return true; } } }, emailOk: function() { $('#component-access-from-forgot-password-type-a-email').css('border', '2px solid green'); $scope.validateForgotpassword().emailInputOk(); }, emailInputOk: function() { $("#component-access-fromlogin-type-a-error-email").removeClass("error"); $("#component-access-fromlogin-type-a-error-email").css('opacity', 0); }, emailError: function() { $("#component-access-from-forgot-password-type-a-email").css('border', '2px solid red'); }, emailInputError: function() { $scope.validateForgotpassword().emailError(); $("#component-access-fromlogin-type-a-error-email").addClass("error"); $("#component-access-fromlogin-type-a-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNullError: function() { $scope.validateForgotpassword().emailError(); $("#component-access-fromlogin-type-a-error-email").addClass("error"); $("#component-access-fromlogin-type-a-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, resetEmail: function() { $("#component-access-from-forgot-password-type-a-email").css('border', ''); $("#component-access-from-forgot-password-type-a-email").val(''); $("#component-access-fromlogin-type-a-error-email").css('opacity', 0); }, reset: function() { $scope.validateForgotpassword().resetEmail(); }, }; return promise; }; /* validateLogin */ $scope.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pagefrom: function() { var load = $('#component-access-from-forgot-password-type-a-from'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnfrom: function() { var load = $('#component-access-from-forgot-password-type-a-from'); if (load.hasClass('active')) { load.removeClass('active'); } }, pageLoad: function() { var load = $('#component-access-from-forgot-password-type-a-load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('#component-access-from-forgot-password-type-a-load'); if (load.hasClass('active')) { load.removeClass('active'); } }, forgotpasswordDone: function() { var load = $('#component-access-from-forgot-password-type-a-done'); if (!load.hasClass('active')) { load.addClass('active'); } }, forgotpasswordUnDone: function() { var load = $('#component-access-from-forgot-password-type-a-done'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitForgotpassword */ $scope.submitForgotpassword = function() { $scope.forgotpassword.email = $('#component-access-from-forgot-password-type-a-email').val(); var userEmail = $scope.forgotpassword.email; console.log("submitForgotpassword", "userEmail : ", userEmail); var userEmailValid = $scope.validateForgotpassword().email(); console.log("submitForgotpassword", "userEmailValid : ", userEmailValid); if (!userEmailValid) { console.log("submitForgotpassword", "return"); return; } $scope.validateForgotpassword().checkEmail(userEmail, function(resultCheck) { console.log("submitForgotpassword", resultCheck); if (resultCheck.ok == 1) { console.log('submitForgotpassword true'); $scope.validateForgotpassword().emailInputError(); $scope.error.email = true; $scope.error.emailExist = true; } else { console.log('submitForgotpassword false'); $scope.sendSubmitForgotpassword(false); } }); }; /* submitForgotpassword */ /* sendSubmitForgotpassword */ $scope.sendSubmitForgotpassword = function(reCheck) { $scope.forgotpassword.pressing = true; var userEmail = $scope.forgotpassword.email; console.log("sendSubmitForgotpassword userEmail : ", userEmail); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $scope.validateForgotpassword().emailInputError(); } else { $scope.validateForgotpassword().emailOk(); } /* email */ if (userEmail.length > 0 && !$scope.helper.isEmail(userEmail)) { $scope.error_email = true; } else { $scope.error_email = false; } } /* loading */ $scope.helper.pageUnfrom(); $scope.helper.pageLoad(); var dataSend = { txt_email: userEmail }; GAEAPI.post('customer/forgot_password', dataSend).then(function(e) { console.log("sendSubmitForgotpassword : complete", e); if (e.ok == 1) { $scope.helper.pageUnLoad(); setTimeout(function() { $scope.helper.forgotpasswordDone(); }, 100); } else { $scope.helper.pageUnLoad(); $scope.helper.pagefrom(); alert("ผิดพลาด กรุณาลองใหม่อีกครั้ง"); return; } }); /* loading */ }; /* sendSubmitForgotpassword */ /* load url */ $scope.viewUrl = function(url) { console.log("viewUrl : ", url); var toUrl = url; console.log("viewUrl : ", toUrl); window.location.href = toUrl; } /* load url */ /* viewPassword */ $scope.viewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); if (t === 'password') { e.setAttribute('type', 'text'); } else { e.setAttribute('type', 'password'); } return true; }; $scope.resetViewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); e.setAttribute('type', 'password'); return true; }; /* viewPassword */ $scope.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } }; return promise; });_ui_share_app.directive('componentAccessFromLogin', function($rootScope, $routeParams) { var componentMain = 'componentAccess'; var componentChild = 'fromlogin'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', domain: '@domain', facebookid: '@facebookid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { /* Variable */ $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.loading = false; $scope.rememberMe = false; $scope.member = [{ input: "", name: "อีเมล Email", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkFormat", format: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, statusError: null, error: "ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)" }, { input: "", name: "รหัสผ่าน Password", showType: "กดเพื่อดู Show Password", typeDefault: "password", type: "password", formatText: "ใส่อย่างน้อย 6 ตัว Should be at least 6 characters", typeFormat: "checkLength", format: 6, statusError: null, error: "ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format" }]; /* Variable */ /* Modify */ $scope.modify = function() { var modify = { checkFormat: function(index) { if ($scope.member[index].type == "password") { $scope.member[index].type = "text"; } else { $scope.member[index].type = "password"; } } }; return modify; }; /* Modify */ /* Format */ $scope.format = function() { var format = { checkFormat: function(format, input, callback) { var format_email = format; var output_check = format_email.test(input); var status_check = false; if (output_check) { status_check = true; } callback(status_check); }, checkLength: function(formatLength, input, callback) { var status_check = false; if (input.length > formatLength) { status_check = true; } callback(status_check); } }; return format; }; /* Format */ /* api */ $scope.api = function() { var api = { checkEmail: function(input, callback) { var dataSend = { txt_email: input }; GAEAPI.post('customer/is_exists_email', dataSend, $scope).then(function(output) { console.log("checkEmail : output : ", output); if (output.ok == 0) { callback(true) } else { callback(false) } }); }, customerTokenLogin: function(email, callback) { var dataSend = { txt_email: email }; GAEAPI.post('customer/token_login', dataSend, $scope).then(function(output) { callback(output) }); }, customerGenerateHashPassword: function(password, token_login, callback) { var dataSend = { 'txt_password': password, 'txt_key_token': token_login.data.key_token, 'txt_secret_token': token_login.data.secret_token }; GAEAPI.post('customer/generate_hash_password', dataSend).then(function(output) { callback(output) }); }, customerLogin: function(email, generate_hash_password, callback) { var dataSend = { 'txt_email': email, 'txt_hash_password': generate_hash_password.data.hash_password }; GAEAPI.post('customer/login', dataSend, $scope).then(function(output) { callback(output) }); } }; return api; }; /* api */ /* Submit */ $scope.submitCallApi = function() { $scope.api().checkEmail($scope.member[0].input, function(resultCheck) { console.log("checkEmail : resultCheck : ", resultCheck); if (resultCheck) { $scope.loading = true; $scope.api().customerTokenLogin($scope.member[0].input, function(token_login) { console.log("submit : token_login : ", token_login); $scope.api().customerGenerateHashPassword($scope.member[1].input, token_login, function(generate_hash_password) { console.log("submit : generate_hash_password : ", generate_hash_password); $scope.api().customerLogin($scope.member[0].input, generate_hash_password, function(login) { console.log("submit : login : ", login); if (login.ok == 1) { var outputLogin = GAEAPI.getValue(login.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(outputLogin, cookie_key, ""); GAEAPI.setUserData(cookie_key, gae_access_token, (typeof rememberMe == true) ? (60 * 60 * 24 * 360) : (60 * 60 * 3)); setTimeout(function() { $scope.loading = false; }, 100); window.location.href = "home"; } else { $scope.member[1].statusError = false; $scope.loading = false; } }); }); }); } else { for (var i = 0; i < $scope.member.length; i++) { console.log("checkEmail : statusError : ", $scope.member[i].statusError); $scope.member[i].statusError = resultCheck; } } }); }; $scope.submit = function() { for (var i = 0; i < $scope.member.length; i++) { console.log("submit : ", $scope.member[i].name, " : input : ", $scope.member[i].input); if ($scope.member[i].typeFormat == "checkFormat") { $scope.format().checkFormat($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } else if ($scope.member[i].typeFormat == "checkLength") { $scope.format().checkLength($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } } for (var i = 0; i < $scope.member.length; i++) { if (!$scope.member[i].statusError) { return; } } $scope.submitCallApi(); }; /* Submit */ /* facebook */ $scope.facebook = function() { var facebook = { installFacebook: function(appId_in, status_in, xfbml_in, version_in) { console.log("installFacebook : appId_in : ", appId_in); console.log("installFacebook : status_in : ", status_in); console.log("installFacebook : xfbml_in : ", xfbml_in); console.log("installFacebook : version_in : ", version_in); window.fbAsyncInit = function() { FB.init({ appId: appId_in, status: status_in, xfbml: xfbml_in, version: version_in }); FB.AppEvents.logPageView(); }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }, loginGetappeasy: function(response, callback) { var dataSend = { txt_fb_access_token: response.authResponse.accessToken, }; UiCustomerBox.api.post("customer/facebook_login", dataSend, $scope).then(function(output) { callback(output) }); }, loginFacebook: function(response, callback) { var status_loginFacebook_callback = false; $scope.loading = true; if (response.status === "connected") { FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) { console.log("FB.api : ", response) }); $scope.facebook().loginGetappeasy(response, function(result) { console.log("loginFacebook : result : ", result); if (result.ok == 1) { UiCustomerBox.callEventScript("on.justLogin", result.data); setTimeout(function() { $scope.loading = false; }, 100); } else { alert("ขออภัย! พบข้อผิดพลาดในการติดต่อระบบ"); } status_loginFacebook_callback = true; callback(status_loginFacebook_callback); }); } else { window.location = encodeURI("https://www.facebook.com/v3.1/dialog/oauth?app_id=" + $scope.facebookid + "&redirect_uri=" + encodeURI($scope.domain) + "&scope=email"); callback(status_loginFacebook_callback); $scope.loading = false; } } } return facebook; }; $scope.facebook().installFacebook($scope.facebookid, true, true, "v3.1"); /* facebook */ /* Submit Facebook */ $scope.submitFacebook = function() { FB.getLoginStatus(function(response) { $scope.facebook().loginFacebook(response, function() {}); }, true); }; /* Submit Facebook */ /* page view */ $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.viewPage = function(page) { $scope.viewRouteParams().view = page; }; /* page view */ }; return promise; });_ui_share_app.directive('componentAccessFromLoginProplugin', function($rootScope, $routeParams) { var componentMain = 'componentAccess'; var componentChild = 'fromloginproplugin'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', domain: '@domain', facebookid: '@facebookid', nextpage: '@nextpage', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { /* Variable */ $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.loading = false; $scope.rememberMe = false; $scope.member = [{ input: "", name: "อีเมล Email", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkFormat", format: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, statusError: null, error: "ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)" }, { input: "", name: "รหัสผ่าน Password", showType: "กดเพื่อดู Show Password", typeDefault: "password", type: "password", formatText: "ใส่อย่างน้อย 6 ตัว Should be at least 6 characters", typeFormat: "checkLength", format: 6, statusError: null, error: "ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format" }]; /* Variable */ /* Modify */ $scope.modify = function() { var modify = { checkFormat: function(index) { if ($scope.member[index].type == "password") { $scope.member[index].type = "text"; } else { $scope.member[index].type = "password"; } } }; return modify; }; /* Modify */ /* Format */ $scope.format = function() { var format = { checkFormat: function(format, input, callback) { var format_email = format; var output_check = format_email.test(input); var status_check = false; if (output_check) { status_check = true; } callback(status_check); }, checkLength: function(formatLength, input, callback) { var status_check = false; if (input.length > formatLength) { status_check = true; } callback(status_check); } }; return format; }; /* Format */ /* api */ $scope.api = function() { var api = { checkEmail: function(input, callback) { var dataSend = { txt_email: input }; GAEAPI.post('customer/is_exists_email', dataSend, $scope).then(function(output) { console.log("checkEmail : output : ", output); if (output.ok == 0) { callback(true) } else { callback(false) } }); }, customerTokenLogin: function(email, callback) { var dataSend = { txt_email: email }; GAEAPI.post('customer/token_login', dataSend, $scope).then(function(output) { callback(output) }); }, customerGenerateHashPassword: function(password, token_login, callback) { var dataSend = { 'txt_password': password, 'txt_key_token': token_login.data.key_token, 'txt_secret_token': token_login.data.secret_token }; GAEAPI.post('customer/generate_hash_password', dataSend).then(function(output) { callback(output) }); }, customerLogin: function(email, generate_hash_password, callback) { var dataSend = { 'txt_email': email, 'txt_hash_password': generate_hash_password.data.hash_password }; GAEAPI.post('customer/login', dataSend, $scope).then(function(output) { callback(output) }); } }; return api; }; /* api */ /* Submit */ $scope.submitCallApi = function() { $scope.api().checkEmail($scope.member[0].input, function(resultCheck) { console.log("checkEmail : resultCheck : ", resultCheck); if (resultCheck) { $scope.loading = true; $scope.api().customerTokenLogin($scope.member[0].input, function(token_login) { console.log("submit : token_login : ", token_login); $scope.api().customerGenerateHashPassword($scope.member[1].input, token_login, function(generate_hash_password) { console.log("submit : generate_hash_password : ", generate_hash_password); $scope.api().customerLogin($scope.member[0].input, generate_hash_password, function(login) { console.log("submit : login : ", login); if (login.ok == 1) { var outputLogin = GAEAPI.getValue(login.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(outputLogin, cookie_key, ""); GAEAPI.setUserData(cookie_key, gae_access_token, (typeof rememberMe == true) ? (60 * 60 * 24 * 360) : (60 * 60 * 3)); setTimeout(function() { $scope.loading = false; }, 100); /* window.location.href = $scope.nextpage; */ window.history.back(); } else { $scope.member[1].statusError = false; $scope.loading = false; } }); }); }); } else { for (var i = 0; i < $scope.member.length; i++) { console.log("checkEmail : statusError : ", $scope.member[i].statusError); $scope.member[i].statusError = resultCheck; } } }); }; $scope.submit = function() { for (var i = 0; i < $scope.member.length; i++) { console.log("submit : ", $scope.member[i].name, " : input : ", $scope.member[i].input); if ($scope.member[i].typeFormat == "checkFormat") { $scope.format().checkFormat($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } else if ($scope.member[i].typeFormat == "checkLength") { $scope.format().checkLength($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } } for (var i = 0; i < $scope.member.length; i++) { if (!$scope.member[i].statusError) { return; } } $scope.submitCallApi(); }; /* Submit */ /* facebook */ $scope.facebook = function() { var facebook = { installFacebook: function(appId_in, status_in, xfbml_in, version_in) { console.log("installFacebook : appId_in : ", appId_in); console.log("installFacebook : status_in : ", status_in); console.log("installFacebook : xfbml_in : ", xfbml_in); console.log("installFacebook : version_in : ", version_in); window.fbAsyncInit = function() { FB.init({ appId: appId_in, status: status_in, xfbml: xfbml_in, version: version_in }); FB.AppEvents.logPageView(); }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }, loginGetappeasy: function(response, callback) { var dataSend = { txt_fb_access_token: response.authResponse.accessToken, }; UiCustomerBox.api.post("customer/facebook_login", dataSend, $scope).then(function(output) { callback(output) }); }, loginFacebook: function(response, callback) { var status_loginFacebook_callback = false; $scope.loading = true; if (response.status === "connected") { FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) { console.log("FB.api : ", response) }); $scope.facebook().loginGetappeasy(response, function(result) { console.log("loginFacebook : result : ", result); if (result.ok == 1) { UiCustomerBox.callEventScript("on.justLogin", result.data); setTimeout(function() { $scope.loading = false; }, 100); } else { alert("ขออภัย! พบข้อผิดพลาดในการติดต่อระบบ"); } status_loginFacebook_callback = true; callback(status_loginFacebook_callback); }); } else { window.location = encodeURI("https://www.facebook.com/v3.1/dialog/oauth?app_id=" + $scope.facebookid + "&redirect_uri=" + encodeURI($scope.domain) + "&scope=email"); callback(status_loginFacebook_callback); $scope.loading = false; } } } return facebook; }; $scope.facebook().installFacebook($scope.facebookid, true, true, "v3.1"); /* facebook */ /* Submit Facebook */ $scope.submitFacebook = function() { FB.getLoginStatus(function(response) { $scope.facebook().loginFacebook(response, function() {}); }, true); }; /* Submit Facebook */ /* page view */ $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.viewPage = function(page) { $scope.viewRouteParams().view = page; }; /* page view */ $scope.isLogin = function() { setTimeout(function() { var isLoginUser = UiCustomerBox.delegate.get.isLogin(); if (!isLoginUser) { console.log("if.isLogin : ", isLoginUser); } else { console.log("else.isLogin : ", isLoginUser); window.location.href = $scope.nextpage; } }, 1000); }; $scope.isLogin(); }; return promise; });_ui_share_app.directive('componentAccessFromLoginTypeA', function($rootScope, $routeParams) { var componentMain = 'componentAccess'; var componentChild = 'fromlogintypea'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.login = { email: '', password: '', remember: false, pressing: false, errore_mail: false, errore_password: false, facebook: false, twitter: false, google: false, }; $scope.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* validateLogin */ $scope.validateLogin = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $scope.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $scope.error.email = false; $scope.error.emailExist = false; $('#component-access-fromlogin-type-a-login-email').css('border', ''); }, focusPassword: function() { $scope.error_password = false; $scope.error.wrong_password = false; $('#component-access-fromlogin-type-a-login-password').css('border', ''); }, email: function() { var v = $('#component-access-fromlogin-type-a-login-email').val(); var t = this; if (v.length <= 0) { $scope.validateLogin().emailInputNullError(); $scope.error_email = false; $scope.error_emailExist = false; return false; } else { var valid = $scope.helper.isEmail(v, true); if (v.length > 0 && !valid) { $scope.validateLogin().emailInputError(); $scope.error_email = true; return false; } else if (v.length > 0 && valid) { $scope.validateLogin().emailOk(); return true; } } }, emailOk: function() { $('#component-access-fromlogin-type-a-login-email').css('border', '2px solid green'); $scope.validateLogin().emailInputOk(); }, emailInputOk: function() { $("#component-access-fromlogin-type-a-login-error-email").removeClass("error"); $("#component-access-fromlogin-type-a-login-error-email").css('opacity', 0); }, emailError: function() { $("#component-access-fromlogin-type-a-login-email").css('border', '2px solid red'); }, emailInputError: function() { $scope.validateLogin().emailError(); $("#component-access-fromlogin-type-a-login-error-email").addClass("error"); $("#component-access-fromlogin-type-a-login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNullError: function() { $scope.validateLogin().emailError(); $("#component-access-fromlogin-type-a-login-error-email").addClass("error"); $("#component-access-fromlogin-type-a-login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#component-access-fromlogin-type-a-login-password').val(); if (v.length <= 0) { $scope.validateLogin().passwordInputNullError(); return false; } if (v.length > 0 && v.length >= 6) { $scope.error_password = false; /*$scope.validateLogin().passwordOk();*/ return true; } else if (v.length > 0 && v.length < 6) { $scope.error_password = true; $scope.validateLogin().passwordInputError(); return false; } }, passwordOk: function() { $("#component-access-fromlogin-type-a-login-password").css('border', '2px solid green'); $scope.validateLogin().passwordInputOk(); }, passwordInputOk: function() { $("#component-access-fromlogin-type-a-login-error-password").removeClass("error"); $("#component-access-fromlogin-type-a-login-error-password").css('opacity', 0); }, passwordError: function() { $("#component-access-fromlogin-type-a-login-password").css('border', '2px solid red'); }, passwordInputError: function() { $scope.validateLogin().passwordError(); $("#component-access-fromlogin-type-a-login-error-password").addClass("error"); $("#component-access-fromlogin-type-a-login-error-password").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputNullError: function() { $scope.validateLogin().passwordError(); $("#component-access-fromlogin-type-a-login-error-password").addClass("error"); $("#component-access-fromlogin-type-a-login-error-password").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetEmail: function() { $("#component-access-fromlogin-type-a-login-email").css('border', ''); $("#component-access-fromlogin-type-a-login-email").val(''); $("#component-access-fromlogin-type-a-login-error-email").css('opacity', 0); }, resetPassword: function() { $("#component-access-fromlogin-type-a-login-password").css('border', ''); $("#component-access-fromlogin-type-a-login-password").val(''); $("#component-access-fromlogin-type-a-login-error-password").css('opacity', 0); }, reset: function() { $scope.validateLogin().resetEmail(); $scope.validateLogin().resetPassword(); }, }; return promise; }; /* validateLogin */ /* load html */ $scope.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.login_v1_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.login_v1_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitLogin */ $scope.submitLogin = function() { $scope.login.email = $('#component-access-fromlogin-type-a-login-email').val(); $scope.login.password = $('#component-access-fromlogin-type-a-login-password').val(); var userEmail = $scope.login.email; var userPass = $scope.login.password; var userEmailValid = $scope.validateLogin().email(); var userPassValid = $scope.validateLogin().password(); console.log("submitLogin", "userEmailValid : ", userEmail, "userPassValid : ", userPass); if (!userEmailValid || !userPassValid) { console.log("submitLogin", "return"); return; } $scope.validateLogin().checkEmail(userEmail, function(resultCheck) { console.log("submitLogin", resultCheck); if (resultCheck.ok == 1) { console.log('submitLogin true'); $scope.validateLogin().emailInputError(); $scope.validateLogin().passwordInputError(); $scope.error.email = true; $scope.error.emailExist = true; } else { console.log('submitLogin false'); return $scope.sendSubmitLogin(false); } }); }; /* submitLogin */ /* sendSubmitLogin */ $scope.sendSubmitLogin = function(reCheck) { $scope.login.pressing = true; var userEmail = $scope.login.email; var userPass = $scope.login.password; if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $scope.validateLogin().emailInputError(); } else { $scope.validateLogin().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $scope.validateLogin().passwordOk(); } else { $scope.validateLogin().passwordInputError(); } /* email */ if (userEmail.length > 0 && !$scope.helper.isEmail(userEmail)) { $scope.error_email = true; } else { $scope.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $scope.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $scope.error_password = true; } if ($scope.error_password || $scope.error_email) { return; } } /* loading */ $scope.helper.pageLoad(); var token_login = {}; var hash_password = {}; var dataSendOne = { 'txt_email': userEmail }; var saveStorageData = {}; GAEAPI.post('customer/token_login', dataSendOne).then(function(e) { token_login = e.data; var dataSendTwo = { 'txt_password': userPass, 'txt_key_token': token_login.key_token, 'txt_secret_token': token_login.secret_token, }; GAEAPI.post('customer/generate_hash_password', dataSendTwo).then(function(ee) { hash_password = ee.data; var dataSendThree = { 'txt_email': userEmail, 'txt_hash_password': hash_password.hash_password }; saveStorageData.data_three = dataSendThree; GAEAPI.post('customer/login', dataSendThree).then(function(eee) { console.log("login : done", eee); if (eee.ok == 1) { var data = GAEAPI.getValue(eee.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(data, cookie_key, ""); saveStorageData.gae_access_token = gae_access_token; console.log("PressLogin -:- CookieLoginDestroy : "); GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 3)); setTimeout(function() { $scope.helper.pageUnLoad(); /*$scope.close();*/ }, 100); window.location.href = "home"; } else { $scope.helper.pageUnLoad(); setTimeout(function() { $scope.validateLogin().passwordInputError(); $scope.error.password = true; $scope.error.wrong_password = true; }, 500); } }); }); }); /* loading */ }; /* sendSubmitLogin */ /* viewPassword */ $scope.viewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); if (t === 'password') { e.setAttribute('type', 'text'); } else { e.setAttribute('type', 'password'); } return true; }; $scope.resetViewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); e.setAttribute('type', 'password'); return true; }; /* viewPassword */ $scope.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* LoginFacebook */ $scope.loginFacebook = function() { FB.getLoginStatus(function(response) { $scope.statusChangeCallback(response); }); } $scope.statusChangeCallback = function(response) { console.log("statusChangeCallback : ", response); if (response.status === 'connected') { console.log("statusChangeCallback : if ", response); } else { console.log("statusChangeCallback : else ", response); } FB.login(function(response) { if (response.authResponse) { console.log("statusChangeCallback response.authResponse : ", response.authResponse); FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) { console.log('statusChangeCallback JSON : , ', JSON.stringify(response)); }); var accessToken = response.authResponse.accessToken; var user_id = response.authResponse.userID; var dataSend = { txt_fb_access_token: accessToken, }; console.log("statusChangeCallback : dataSend : ", dataSend); UiCustomerBox.api.post("customer/facebook_login", dataSend).then(function(res) { console.log("customer/facebook_login : res", res); if (res.ok == 1) { UiCustomerBox.callEventScript("on.justLogin", res.data); setTimeout(function() { $scope.helper.pageUnLoad(); /*$scope.close();*/ }, 100); /*location.reload();*/ window.location.href = "home"; } else { error.log('statusChangeCallback error.'); } }); } else { console.log('User cancelled login or did not fully authorize.'); } }, { scope: "email" }) } /* LoginFacebook */ }; return promise; });_ui_share_app.directive('componentAccessFromRegister', function($rootScope, $routeParams) { var componentMain = 'componentAccess'; var componentChild = 'fromregister'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { /* Variable */ $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.loading = false; $scope.welcome = false; $scope.rememberMe = false; $scope.member = [{ input: "", name: "ชื่อจริง Firstname", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkLength", format: 1, statusError: null, error: "ตรวจสอบรูปแบบชื่อ Please check your format" }, { input: "", name: "นามสกุลจริง Lastname", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkLength", format: 1, statusError: null, error: "ตรวจสอบรูปแบบนามสกุล Please check your format)" }, { input: "", name: "เบอร์โทรศัพท์ Mobile Phone", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkFormat", format: /^(([0-9]{8,10}))$/, statusError: null, error: "ตรวจสอบรูปแบบนามสกุล Please check your format)" }, { input: "", name: "อีเมล Email", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkFormat", format: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, statusError: null, error: "ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)" }, { input: "", name: "รหัสผ่าน Password", showType: "กดเพื่อดู Show Password", typeDefault: "password", type: "password", formatText: "ใส่อย่างน้อย 6 ตัว Should be at least 6 characters", typeFormat: "checkLength", format: 6, statusError: null, error: "ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format" }]; /* Variable */ /* Modify */ $scope.modify = function() { var modify = { checkFormat: function(index) { if ($scope.member[index].type == "password") { $scope.member[index].type = "text"; } else { $scope.member[index].type = "password"; } } }; return modify; }; /* Modify */ /* Format */ $scope.format = function() { var format = { checkFormat: function(format, input, callback) { var format_email = format; var output_check = format_email.test(input); var status_check = false; if (output_check) { status_check = true; } callback(status_check); }, checkLength: function(formatLength, input, callback) { var status_check = false; if (input.length > formatLength) { status_check = true; } callback(status_check); } }; return format; }; /* Format */ /* api */ $scope.api = function() { var api = { checkEmail: function(input, callback) { var dataSend = { txt_email: input }; GAEAPI.post('customer/is_exists_email', dataSend, $scope).then(function(output) { console.log("checkEmail : output : ", output); if (output.ok == 1) { callback(true) } else { callback(false) } }); }, checkOk: function(data, callback) { var check_ok = false; if (data.ok == 1) { check_ok = true; } callback(check_ok); }, customerRegister: function(first, last, mobile, email, password, callback) { var dataSend = { 'txt_first_name': first, 'txt_last_name': last, 'txt_mobile_phone': mobile, 'txt_email': email, 'txt_password': password }; console.log("customerRegister : dataSend : ", dataSend); GAEAPI.post('customer/register', dataSend, $scope).then(function(output) { console.log("customerRegister : output : ", output); $scope.api().checkOk(output, function(check_ok) { callback(check_ok) }); }); } }; return api; }; /* api */ /* Submit */ $scope.submitCallApi = function() { $scope.api().checkEmail($scope.member[3].input, function(resultCheck) { console.log("submitCallApi : checkEmail : resultCheck : ", resultCheck); if (resultCheck) { $scope.loading = true; $scope.api().customerRegister($scope.member[0].input, $scope.member[1].input, $scope.member[2].input, $scope.member[3].input, $scope.member[4].input, function(check_ok) { console.log("submitCallApi : customerRegister : check_ok : ", check_ok); if (check_ok) { setTimeout(function() { $scope.loading = false; $scope.welcome = true; }, 100); } else { alert("ขออภัย! พบข้อผิดพลาดในการติดต่อระบบ"); $scope.loading = false; } }); } else { $scope.member[3].statusError = resultCheck; } }); }; $scope.submit = function() { for (var i = 0; i < $scope.member.length; i++) { console.log("submit : ", $scope.member[i].name, " : input : ", $scope.member[i].input); if ($scope.member[i].typeFormat == "checkFormat") { $scope.format().checkFormat($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } else if ($scope.member[i].typeFormat == "checkLength") { $scope.format().checkLength($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } } for (var i = 0; i < $scope.member.length; i++) { if (!$scope.member[i].statusError) { return; } } $scope.submitCallApi(); }; /* Submit */ /* page view */ $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.viewPage = function(page) { $scope.welcome = false; $scope.viewRouteParams().view = page; }; $scope.windowLocationHref = function(page) { window.location.href = page; }; /* page view */ }; return promise; });_ui_share_app.directive('componentAccessFromRegisterProplugin', function($rootScope, $routeParams) { var componentMain = 'componentAccess'; var componentChild = 'fromregisterproplugin'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { /* Variable */ $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.loading = false; $scope.welcome = false; $scope.rememberMe = false; $scope.member = [{ input: "", name: "ชื่อจริง Firstname", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkLength", format: 1, statusError: null, error: "ตรวจสอบรูปแบบชื่อ Please check your format" }, { input: "", name: "นามสกุลจริง Lastname", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkLength", format: 1, statusError: null, error: "ตรวจสอบรูปแบบนามสกุล Please check your format)" }, { input: "", name: "อีเมล Email", showType: "", typeDefault: "text", type: "text", formatText: "", typeFormat: "checkFormat", format: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, statusError: null, error: "ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)" }, { input: "", name: "รหัสผ่าน Password", showType: "กดเพื่อดู Show Password", typeDefault: "password", type: "password", formatText: "ใส่อย่างน้อย 6 ตัว Should be at least 6 characters", typeFormat: "checkLength", format: 6, statusError: null, error: "ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format" }]; /* Variable */ /* Modify */ $scope.modify = function() { var modify = { checkFormat: function(index) { if ($scope.member[index].type == "password") { $scope.member[index].type = "text"; } else { $scope.member[index].type = "password"; } } }; return modify; }; /* Modify */ /* Format */ $scope.format = function() { var format = { checkFormat: function(format, input, callback) { var format_email = format; var output_check = format_email.test(input); var status_check = false; if (output_check) { status_check = true; } callback(status_check); }, checkLength: function(formatLength, input, callback) { var status_check = false; if (input.length > formatLength) { status_check = true; } callback(status_check); } }; return format; }; /* Format */ /* api */ $scope.api = function() { var api = { checkEmail: function(input, callback) { var dataSend = { txt_email: input }; GAEAPI.post('customer/is_exists_email', dataSend, $scope).then(function(output) { console.log("checkEmail : output : ", output); if (output.ok == 1) { callback(true) } else { callback(false) } }); }, checkOk: function(data, callback) { var check_ok = false; if (data.ok == 1) { check_ok = true; } callback(check_ok); }, customerRegister: function(first, last, email, password, callback) { var dataSend = { 'txt_first_name': first, 'txt_last_name': last, 'txt_email': email, 'txt_password': password }; console.log("customerRegister : dataSend : ", dataSend); GAEAPI.post('customer/register', dataSend, $scope).then(function(output) { console.log("customerRegister : output : ", output); $scope.api().checkOk(output, function(check_ok) { callback(check_ok) }); }); } }; return api; }; /* api */ /* Submit */ $scope.submitCallApi = function() { $scope.api().checkEmail($scope.member[2].input, function(resultCheck) { console.log("submitCallApi : checkEmail : resultCheck : ", resultCheck); if (resultCheck) { $scope.loading = true; $scope.api().customerRegister($scope.member[0].input, $scope.member[1].input, $scope.member[2].input, $scope.member[3].input, function(check_ok) { console.log("submitCallApi : customerRegister : check_ok : ", check_ok); if (check_ok) { setTimeout(function() { $scope.loading = false; $scope.welcome = true; }, 100); } else { alert("ขออภัย! พบข้อผิดพลาดในการติดต่อระบบ"); $scope.loading = false; } }); } else { $scope.member[2].statusError = resultCheck; } }); }; $scope.submit = function() { for (var i = 0; i < $scope.member.length; i++) { console.log("submit : ", $scope.member[i].name, " : input : ", $scope.member[i].input); if ($scope.member[i].typeFormat == "checkFormat") { $scope.format().checkFormat($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } else if ($scope.member[i].typeFormat == "checkLength") { $scope.format().checkLength($scope.member[i].format, $scope.member[i].input, function(status_check) { $scope.member[i].statusError = status_check; }); } } for (var i = 0; i < $scope.member.length; i++) { if (!$scope.member[i].statusError) { return; } } $scope.submitCallApi(); }; /* Submit */ /* page view */ $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.viewPage = function(page) { $scope.welcome = false; $scope.viewRouteParams().view = page; }; $scope.windowLocationHref = function(page) { window.location.href = page; }; /* page view */ }; return promise; });_ui_share_app.directive('componentAccessFromRegisterTypeA', function($rootScope, $routeParams) { var componentMain = 'componentAccess'; var componentChild = 'fromregistertypea'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* register model */ $scope.register = { firstname: '', lastname: '', email: '', password: '', pressing: false, errore_mail: false, errore_password: false, }; $scope.error = { firstnameExist: false, lastnameExist: false, emailExist: false, firstname: false, lastname: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* register model */ /* validateRegister */ $scope.validateRegister = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $scope.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusFirstname: function() { $scope.error.firstname = false; $scope.error.firstnameExist = false; $('#component-access-from-register-type-a-firstname').css('border', ''); }, focusLastname: function() { $scope.error.lastname = false; $scope.error.lastnameExist = false; $('#component-access-from-register-type-a-lastname').css('border', ''); }, focusEmail: function() { $scope.error.email = false; $scope.error.emailExist = false; $('#component-access-from-register-type-a-email').css('border', ''); }, focusPassword: function() { $scope.error_password = false; $scope.error.wrong_password = false; $('#component-access-from-register-type-a-password').css('border', ''); }, firstname: function() { var v = $('#component-access-from-register-type-a-firstname').val(); var t = this; var valid = $scope.helper.isFirstname(v, true); console.log("firstname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $scope.validateRegister().firstnameInputNullError(); $scope.error_firstname = false; $scope.error_firstnameExist = false; return false; } else { if (v.length > 0 && !valid) { $scope.validateRegister().firstnameInputError(); $scope.error_firstname = true; return false; } else if (v.length > 0 && valid) { $scope.validateRegister().firstnameOk(); return true; } } }, lastname: function() { var v = $('#component-access-from-register-type-a-lastname').val(); var t = this; var valid = $scope.helper.isLastname(v, true); console.log("lastname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $scope.validateRegister().lastnameInputNullError(); $scope.error_lastname = false; $scope.error_lastnameExist = false; return false; } else { if (v.length > 0 && valid) { $scope.validateRegister().lastnameOk(); return true; } else { $scope.validateRegister().lastnameInputError(); $scope.error_lastname = true; return false; } } }, email: function() { var v = $('#component-access-from-register-type-a-email').val(); var t = this; if (v.length <= 0) { $scope.validateRegister().emailInputNullError(); $scope.error_email = false; $scope.error_emailExist = false; return false; } else { var valid = $scope.helper.isEmail(v, true); if (v.length > 0 && !valid) { $scope.validateRegister().emailInputError(); $scope.error_email = true; return false; } else if (v.length > 0 && valid) { $scope.validateRegister().emailOk(); return true; } } }, firstnameOk: function() { $('#component-access-from-register-type-a-firstname').css('border', '2px solid green'); $scope.validateRegister().firstnameInputOk(); }, lastnameOk: function() { $('#component-access-from-register-type-a-lastname').css('border', '2px solid green'); $scope.validateRegister().lastnameInputOk(); }, emailOk: function() { $('#component-access-from-register-type-a-email').css('border', '2px solid green'); $scope.validateRegister().emailInputOk(); }, firstnameInputOk: function() { $("#component-access-fromlogin-type-a-error-firstname").removeClass("error"); $("#component-access-fromlogin-type-a-error-firstname").css('opacity', 0); }, lastnameInputOk: function() { $("#component-access-fromlogin-type-a-error-lastname").removeClass("error"); $("#component-access-fromlogin-type-a-error-lastname").css('opacity', 0); }, emailInputOk: function() { $("#component-access-fromlogin-type-a-error-email").removeClass("error"); $("#component-access-fromlogin-type-a-error-email").css('opacity', 0); }, firstnameError: function() { $("#component-access-from-register-type-a-firstname").css('border', '2px solid red'); }, lastnameError: function() { $("#component-access-from-register-type-a-lastname").css('border', '2px solid red'); }, emailError: function() { $("#component-access-from-register-type-a-email").css('border', '2px solid red'); }, firstnameInputError: function() { $scope.validateRegister().firstnameError(); $("#component-access-fromlogin-type-a-error-firstname").addClass("error"); $("#component-access-fromlogin-type-a-error-firstname").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputError: function() { $scope.validateRegister().lastnameError(); $("#component-access-fromlogin-type-a-error-lastname").addClass("error"); $("#component-access-fromlogin-type-a-error-lastname").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format)'); }, emailInputRepeatedly: function() { $scope.validateRegister().emailError(); $("#component-access-fromlogin-type-a-error-email").addClass("error"); $("#component-access-fromlogin-type-a-error-email").css('opacity', 1).html('อีเมลนี้มีการลงทะเบียนเป็นสมาชิกแล้ว Email already exists'); }, passwordInputRepeatedly: function() { $("#component-access-from-register-type-a-password").css('border', '1px solid #dddddd'); }, emailInputError: function() { $scope.validateRegister().emailError(); $("#component-access-fromlogin-type-a-error-email").addClass("error"); $("#component-access-fromlogin-type-a-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, firstnameInputNullError: function() { $scope.validateRegister().firstnameError(); $("#component-access-fromlogin-type-a-error-firstname").addClass("error"); $("#component-access-fromlogin-type-a-error-firstname").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputNullError: function() { $scope.validateRegister().lastnameError(); $("#component-access-fromlogin-type-a-error-lastname").addClass("error"); $("#component-access-fromlogin-type-a-error-lastname").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format)'); }, emailInputNullError: function() { $scope.validateRegister().emailError(); $("#component-access-fromlogin-type-a-error-email").addClass("error"); $("#component-access-fromlogin-type-a-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#component-access-from-register-type-a-password').val(); if (v.length <= 0) { $scope.validateRegister().passwordInputNullError(); return false; } if (v.length > 0 && v.length >= 6) { $scope.error_password = false; $scope.validateRegister().passwordOk(); return true; } else if (v.length > 0 && v.length < 6) { $scope.error_password = true; $scope.validateRegister().passwordInputError(); return false; } }, passwordOk: function() { $("#component-access-from-register-type-a-password").css('border', '2px solid green'); $scope.validateRegister().passwordInputOk(); }, passwordInputOk: function() { $("#component-access-fromlogin-type-a-error-password").removeClass("error"); $("#component-access-fromlogin-type-a-error-password").css('opacity', 0); }, passwordError: function() { $("#component-access-from-register-type-a-password").css('border', '2px solid red'); }, passwordInputError: function() { $scope.validateRegister().passwordError(); $("#component-access-fromlogin-type-a-error-password").addClass("error"); $("#component-access-fromlogin-type-a-error-password").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputNullError: function() { $scope.validateRegister().passwordError(); $("#component-access-fromlogin-type-a-error-password").addClass("error"); $("#component-access-fromlogin-type-a-error-password").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetFirstname: function() { $("#component-access-from-register-type-a-firstname").css('border', ''); $("#component-access-from-register-type-a-firstname").val(''); $("#component-access-fromlogin-type-a-error-firstname").css('opacity', 0); }, resetLastname: function() { $("#component-access-from-register-type-a-lastname").css('border', ''); $("#component-access-from-register-type-a-lastname").val(''); $("#component-access-fromlogin-type-a-error-lastname").css('opacity', 0); }, resetEmail: function() { $("#component-access-from-register-type-a-email").css('border', ''); $("#component-access-from-register-type-a-email").val(''); $("#component-access-fromlogin-type-a-error-email").css('opacity', 0); }, resetPassword: function() { $("#component-access-from-register-type-a-password").css('border', ''); $("#component-access-from-register-type-a-password").val(''); $("#component-access-fromlogin-type-a-error-password").css('opacity', 0); }, reset: function() { $scope.validateRegister().resetFirstname(); $scope.validateRegister().resetLastname(); $scope.validateRegister().resetEmail(); $scope.validateRegister().resetPassword(); }, }; return promise; }; /* validateRegister */ /* load html */ $scope.viewHtml = function(viewName) { var html = path + viewName; return html; }; $scope.whenOnLoad = function(shopId) {}; $scope.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isFirstname: function(firstname) { if (firstname.length > 1) { return true; } else { return false; } }, isLastname: function(lastname) { if (lastname.length > 1) { return true; } else { return false; } }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageFrom: function() { var load = $('#component-access-from-register-type-a-from'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnFrom: function() { var load = $('#component-access-from-register-type-a-from'); if (load.hasClass('active')) { load.removeClass('active'); } }, pageLoad: function() { var load = $('#component-access-from-register-type-a-load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('#component-access-from-register-type-a-load'); if (load.hasClass('active')) { load.removeClass('active'); } }, registerDone: function() { var load = $('#component-access-from-register-type-a-done'); if (!load.hasClass('active')) { load.addClass('active'); } }, registerUnDone: function() { var load = $('component-access-from-register-type-a-done'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitRegister */ $scope.submitRegister = function() { $scope.register.firstname = $('#component-access-from-register-type-a-firstname').val(); $scope.register.lastname = $('#component-access-from-register-type-a-lastname').val(); $scope.register.email = $('#component-access-from-register-type-a-email').val(); $scope.register.password = $('#component-access-from-register-type-a-password').val(); var userFirstname = $scope.register.firstname; var userLastname = $scope.register.lastname; var userEmail = $scope.register.email; var userPass = $scope.register.password; var userFirstnameValid = $scope.validateRegister().firstname(); var userLastnameValid = $scope.validateRegister().lastname(); var userEmailValid = $scope.validateRegister().email(); var userPassValid = $scope.validateRegister().password(); console.log("submitRegister", "userFirstnameValid : ", userFirstnameValid, "userLastnameValid : ", userLastnameValid, "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); if (!userFirstnameValid || !userLastnameValid || !userEmailValid || !userPassValid) { console.log("submitRegister", "return"); return; } $scope.validateRegister().checkEmail(userEmail, function(resultCheck) { console.log("submitRegister", resultCheck); if (resultCheck.ok == 0) { console.log('submitRegister true'); $scope.validateRegister().emailInputRepeatedly(); $scope.validateRegister().passwordInputRepeatedly(); } else { console.log('submitRegister false'); $scope.sendSubmitRegister(false); } }); }; /* submitRegister */ /* sendSubmitRegister */ $scope.sendSubmitRegister = function(reCheck) { $scope.register.pressing = true var userFirstname = $scope.register.firstname; var userLastname = $scope.register.lastname;; var userEmail = $scope.register.email; var userPass = $scope.register.password; console.log("sendSubmitRegister", reCheck); if (reCheck) { /* if error : firstname */ if (userFirstname.length <= 0) { $scope.validateRegister().firstnameInputError(); } else { $scope.validateRegister().firstnameOk(); } /* if error : lastname */ if (userLastname.length <= 0) { $scope.validateRegister().lastnameInputError(); } else { $scope.validateRegister().lastnameOk(); } /* if error : user */ if (userEmail.length <= 0) { $scope.validateRegister().emailInputError(); } else { $scope.validateRegister().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $scope.validateRegister().passwordOk(); } else { $scope.validateRegister().passwordInputError(); } /* firstname */ if (userFirstname.length > 0 && !$scope.helper.isFirstname(userFirstname)) { $scope.error_firstname = true; } else { $scope.error_firstname = false; } /* lastname */ if (userLastname.length > 0 && !$scope.helper.isLastname(userLastname)) { $scope.error_lastname = true; } else { $scope.error_lastname = false; } /* email */ if (userEmail.length > 0 && !$scope.helper.isEmail(userEmail)) { $scope.error_email = true; } else { $scope.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $scope.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $scope.error_password = true; } console.log("sendSubmitRegister", "error_firstname : ", $scope.error_firstname, "error_lastname : ", $scope.error_lastname, "error_email : ", $scope.error_email, "error_password : ", $scope.error_password); if ($scope.error_firstname || $scope.error_lastname || $scope.error_email || $scope.error_password) { console.log("sendSubmitRegister return"); return; } } /* loading */ $scope.helper.pageUnFrom(); $scope.helper.pageLoad(); var dataSend = { 'txt_first_name': userFirstname, 'txt_last_name': userLastname, 'txt_email': userEmail, 'txt_password': userPass }; console.log("sendSubmitRegister txt_email :", dataSend); GAEAPI.post("ui/api/ui_customer_box/customer/register", dataSend).then(function(output) { console.log("sendSubmitRegister register", output); if (output.ok == 1) { $scope.helper.pageUnLoad(); setTimeout(function() { $scope.helper.registerDone(); }, 100); } else { $scope.helper.pageUnLoad(); $scope.helper.pageFrom(); alert("Register ผิดพลาด! กรุณาลองใหม่อีกครั้ง"); } }); /* loading */ }; /* sendSubmitRegister */ /* viewPassword */ $scope.viewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); if (t === 'password') { e.attr('type', 'text'); } else { e.attr('type', 'password'); } }; $scope.resetViewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); e.attr('type', 'password'); }; /* viewPassword */ $scope.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $scope.isOpen = false; $scope.open = function() { $scope.resetViewPassword('component-access-from-register-type-a-password'); $scope.validateRegister().reset(); $(".register_overlay").addClass("is_open"); $('body').css({ 'overflow': 'hidden' }); timerAdjustOpen = setTimeout(function() { $(".register.from_background").addClass("is_open"); }, 100); }; /* Open */ /* load url */ $scope.viewUrl = function(url) { console.log("viewUrl : ", url); var toUrl = url; console.log("viewUrl : ", toUrl); window.location.href = toUrl; } /* load url */ /* login */ $scope.login = function() { $scope.close(); $scope.helper.registerUnDone(); $inloginPopup.open(); } /* login */ /* toHome */ $scope.toHome = function() { $scope.helper.registerUnDone(); window.location.href = 'home'; }; /* toHome */ }; return promise; }); _ui_share_app.directive('componentAlbumA', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentAlbumA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { type: '@type', imgpath: '@imgpath', uselightbox: '@uselightbox', callback: '@callback', menu: '@menu', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; $scope._use_callback = (typeof $scope.callback !== 'undefined' && $scope.callback !== '') ? true : false; $scope._no_menu = (typeof $scope.menu !== 'undefined' && $scope.menu !== '') ? false : true; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._getIdFromUrl = function(rawRouteParams){ var a = rawRouteParams; var b = a.split("-"); if(b.length > 0 && a.indexOf("-") !== -1){ return b[0]; } else { return a; } }; /* Build dummy data by gallery type * @params {typeName} type of page * @return array */ $scope.buildDummyByType = function(typeName){ switch(typeName){ case 'gallery': var d = []; for(var i = 0; i < 6; i++){ var item = { 'gallery_badge': [{badge_id:18}], 'gallery_id': (i+1), 'gallery_name': 'Gallery ' + (i+1), 'gallery_image': [{'image_url':'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}] }; d.push(item); } $scope.data_gallery_list = d; $scope.data_gallery_list_done = true; break; case 'gallery_id': var d = []; for(var i = 0; i < 6; i++){ var item = { 'gallery_badge': [{badge_id:18}], 'image_group_id': 10+(i+1), 'image_group_name': 'Album list number ' + (i+1), 'image_group_image': [{'image_url':'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}] }; d.push(item); } $scope.data_album_list = d; break; case 'photo_list': var d = []; for(var i = 0; i < 6; i++){ var item = { 'image_url':'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif', }; d.push(item); } $scope.data_photo_list = d; break; } }; /* Get all gellery for first time*/ $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; $scope.galleryInit = function(){ $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; var d = { 'cur_page':1, 'per_page':30, 'txt_filter_json': JSON.stringify({"badge_id_array":[18]}) }; GAEAPI.get('gallery/lists',d,$scope).then(function(e){ $scope.data_gallery_list = (e.ok == 1) ? e.data.dataList : []; $scope.data_gallery_list_done = true; if($scope.data_gallery_list.length <= 0 && $scope._use_callback){ $scope.buildDummyByType('gallery'); } }); }; $scope.galleryInit(); /* Get album list inside gallery id */ $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(gallery_id){ $scope.data_album_list = []; var d = { 'cur_page':1, 'per_page':32, 'txt_filter_json': JSON.stringify({"gallery_id_array":[gallery_id]}) }; GAEAPI.get('image_group/lists',d,$scope).then(function(res){ if(res.ok == 1){ $scope.data_album_list = (res.ok == 1) ? res.data.dataList : []; if($scope.data_album_list.length <= 0 && $scope._use_callback){ $scope.buildDummyByType('gallery_id'); } } }); }; /* Get photo list inside (gallery id => album id) */ $scope.data_photo_list = []; $scope.getPhotoListByAlbumId = function(album_id){ $scope.data_photo_list = []; var d = { 'cur_page':1, 'per_page':50, 'txt_filter_json': JSON.stringify({"image_group_id_array":[album_id]}) }; GAEAPI.get('image/lists',d,$scope).then(function(res){ if(res.ok == 1){ $scope.data_photo_list = (res.ok == 1) ? res.data.dataList : []; if($scope.data_photo_list.length <= 0 && $scope._use_callback){ $scope.buildDummyByType('photo_list'); } } }); }; $scope.checkPageType = function(){ if(typeof $routeParams.view_album_id !== 'undefined' && $routeParams.view_album_id != '' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id !== ''){ return 'view_album_id'; } else if(typeof $routeParams.view_album_id === 'undefined' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id != ''){ return 'album_id'; } else { return 'gallery'; } }; $scope.pageType = $scope.checkPageType() || ""; switch($scope.pageType){ case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; default: break; } /* When route change start */ $rootScope.$on('$routeChangeStart', function (event, current, prev) { var elementName = '[data-iddd="'+$scope._key()+'"]'; var slickIntance = $(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider') || false; if (slickIntance && $scope.type === 'portfolio-carousel-boxed') { $(elementName).slick('unslick'); $scope._uniqueKey = ''; } }); /* When route change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { $scope.pageType = $scope.checkPageType(); switch($scope.pageType){ case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; } }); /* Currnet Params */ $scope.viewRouteParams = function(){ return $routeParams; }; /* Check if seo website */ $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Build String title url */ $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; $scope.checkUrlActive = function(activeString){ return (window.location.href.indexOf(activeString) != -1) ? true : false; }; /* Broadcase event -> do something */ $rootScope.$on('repeatend', function() { if($scope.pageType === 'view_album_id'){ /* Check Lightbox Enable/Disable */ $('a[data-photo-index]').each(function(idx,obj){ if($scope._use_lightBox){ $(this).attr('data-lightbox','view-gallery'); } else { $(this).attr('target','_blank'); $(this).attr('data-nolightbox','true'); $(this).removeAttr('data-lightbox'); } }); } if($scope.type === 'portfolio-carousel-boxed' && $scope.pageType == 'view_album_id'){ $('.animateSlideFromRight').each(function(i, object){ if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function () { $(this).addClass('animateEnded').dequeue(); }); } }); return; } else if($scope.type ==='portfolio-images-boxed'){ $('.animteZoomToNormal').each(function(i, object){ if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function () { $(this).addClass('animateEnded').dequeue(); }); } }); return; } if($('[data-iddd="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.slideInit(); }, 500); } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function(){ var elementName = '[data-iddd="'+$scope._key()+'"]'; var optionsParmas = { autoplay: false, slidesToShow: 3, slidesToScroll: 3, dots: true, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false, slideFromRight: true, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } }); }; $scope.getGridItemWidth = function(){ return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx){ if($scope._use_lightBox){ $('a[data-index="'+idx+'"]').attr('data-lightbox','gallery-view'); } else { $('a[data-index="'+idx+'"]').attr('data-nolightbox','yes'); } }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.setdispay = function (imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow','hidden'); } $scope.setdispayclose = function (imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow','visible'); } $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } console.log("test_test_test :",$scope.viewRouteParams()); }; return promise; }); _ui_share_app.directive('componentAlbumAa', function($rootScope, $routeParams, sliderProvider, carouselData, $location) { var templateName = 'componentAlbumAa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', margin: '@margin', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = { name: "trumpComponentAlbums", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._margin = ($scope.margin != undefined && $scope.margin != "") ? { margin: $scope.margin } : { margin: 0 }; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getGalleryId: function(params, callback) { var _self = this; var gallery_id = (params.gallery_id != undefined) ? params.gallery_id.split("-", 1).join("") : false; _self.consoleLog("getGalleryId", "gallery_id", gallery_id); callback(gallery_id); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; /* get api */ $scope.data_api = { load_more: { load: false, cur_page: 1, per_page: 12, total_rows: 0 }, gallery_id: { data_send: {}, api: "gallery/id", ok: false, data_array: [], data_array_state: { load: false, done: false } }, album: { data_send: {}, api: "image_group/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.loadMore = function() { if (!$scope.data_api.load_more.load) { $scope.data_api.load_more.cur_page++; $scope.data_api.load_more.load = true; $scope.getData().getRouteParams(function(_self, params, state) { _self.formatDataSend($scope.data_api.album, function(res_data) { _self.getGalleryId(params, function(res_gallery_id) { var filter_json = { "gallery_id_array": [res_gallery_id] }; var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'image_group_create_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var oldData = res_data.data_array; res_data.data_array = oldData.concat(res_api.data.dataList); angular.forEach(res_data.data_array, function(item, index) { _self.getNameUrl(res_data.data_array[index].image_group_name, function(res_title) { res_data.data_array[index].image_group_name_url = res_title; }); }); $scope.data_api.load_more.total_rows = res_api.data.total_rows; } else { $scope.data_api.load_more.cur_page--; } $scope.data_api.load_more.load = false; }); }); }); }); }); } } $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.gallery_id.data_array_state = state; _self.formatDataSend($scope.data_api.gallery_id, function(res_data) { _self.getGalleryId(params, function(res_gallery_id) { var dataSend = { 'txt_gallery_id': res_gallery_id }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); $scope.data_api.album.data_array_state = state; _self.formatDataSend($scope.data_api.album, function(res_data) { _self.getGalleryId(params, function(res_gallery_id) { var filter_json = { "gallery_id_array": [res_gallery_id] }; var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'image_group_create_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getNameUrl(res_data.data_array[index].image_group_name, function(res_title) { res_data.data_array[index].image_group_name_url = res_title; }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; }); }); }); }); }); /* get api */ }; return promise; }); _ui_share_app.directive('componentAlbumC', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentAlbumC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { type: '@type', imgpath: '@imgpath', uselightbox: '@uselightbox', callback: '@callback', menu: '@menu', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; $scope._use_callback = (typeof $scope.callback !== 'undefined' && $scope.callback !== '') ? true : false; $scope._no_menu = (typeof $scope.menu !== 'undefined' && $scope.menu !== '') ? false : true; $scope.pageType = 'view_album_id'; $scope.gallery_id = $routeParams.gallery_id || 0; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._getIdFromUrl = function(rawRouteParams){ var a = rawRouteParams; var b = a.split("-"); if(b.length > 0 && a.indexOf("-") !== -1){ return b[0]; } else { return a; } }; $scope.$watch('gallery_id', function(newValue, oldValue) { console.log("Watch Referral", newValue); if (newValue != 0) { $scope.getAlbumListByGalleryId(newValue); } else if (newValue == 0 || !newValue) { return; } }); /* Get album list inside gallery id */ $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(new_ref){ $scope.data_album_list = []; var d = { 'cur_page':1, 'per_page':32, 'txt_sortby':'image_group_name_ASC', 'txt_filter_json': JSON.stringify({"gallery_id_array":[new_ref]}) }; GAEAPI.get('image_group/lists',d,$scope).then(function(res){ if(res.ok == 1){ $scope.data_album_list = (res.ok == 1) ? res.data.dataList : []; var temp = []; for(var i=0;i album id) */ /* $scope.data_photo_list = [];*/ /* $scope.getPhotoListByAlbumId = function(album_id){ $scope.data_photo_list = []; $scope.text_test = []; for(var i=0;i do something */ $rootScope.$on('repeatend', function() { if($scope.pageType === 'view_album_id'){ /* Check Lightbox Enable/Disable */ $('a[data-photo-index]').each(function(idx,obj){ if($scope._use_lightBox){ $(this).attr('data-lightbox','view-gallery'); } else { $(this).attr('target','_blank'); $(this).attr('data-nolightbox','true'); $(this).removeAttr('data-lightbox'); } }); } if($scope.type === 'portfolio-carousel-boxed' && $scope.pageType == 'view_album_id'){ $('.animateSlideFromRight').each(function(i, object){ if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function () { $(this).addClass('animateEnded').dequeue(); }); } }); return; } else if($scope.type ==='portfolio-images-boxed'){ $('.animteZoomToNormal').each(function(i, object){ if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function () { $(this).addClass('animateEnded').dequeue(); }); } }); return; } if($('[data-iddd="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.slideInit(); }, 500); } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function(){ var elementName = '[data-iddd="'+$scope._key()+'"]'; var optionsParmas = { autoplay: false, slidesToShow: 3, slidesToScroll: 3, dots: true, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false, slideFromRight: true, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } }); }; $scope.getGridItemWidth = function(){ return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx){ if($scope._use_lightBox){ $('a[data-index="'+idx+'"]').attr('data-lightbox','gallery-view'); } else { $('a[data-index="'+idx+'"]').attr('data-nolightbox','yes'); } }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.setdispay = function (imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow','hidden'); } $scope.setdispayclose = function (imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow','visible'); } $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } }; return promise; }); _ui_share_app.directive('componentAlbumD', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentAlbumD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { type: '@type', imgpath: '@imgpath', uselightbox: '@uselightbox', callback: '@callback', menu: '@menu', albumid: '@albumid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; $scope._use_callback = (typeof $scope.callback !== 'undefined' && $scope.callback !== '') ? true : false; $scope._no_menu = (typeof $scope.menu !== 'undefined' && $scope.menu !== '') ? false : true; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(album_id) { $scope.data_album_list = []; var d = { 'txt_image_group_id': album_id }; GAEAPI.get('image_group/id', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_album_list = (res.ok == 1) ? res.data : ''; } }); }; /* Get photo list inside (gallery id => album id) */ $scope.data_photo_list = []; $scope.getPhotoListByAlbumId = function(album_id) { $scope.data_photo_list = []; var d = { 'cur_page': 1, 'per_page': 50, 'txt_filter_json': JSON.stringify({ "image_group_id_array": [album_id] }) }; GAEAPI.get('image/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_photo_list = (res.ok == 1) ? res.data.dataList : []; console.log("asasaa :", $scope.data_photo_list); } }); }; var album_id = $scope.albumid; $scope.getPhotoListByAlbumId(album_id); $scope.getAlbumListByGalleryId(album_id); /* Currnet Params */ $scope.viewRouteParams = function() { return $routeParams; }; /* Check if seo website */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Build String title url */ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.checkUrlActive = function(activeString) { return (window.location.href.indexOf(activeString) != -1) ? true : false; }; /* Broadcase event -> do something */ $rootScope.$on('repeatend', function() { if ($scope.pageType === 'view_album_id') { /* Check Lightbox Enable/Disable */ $('a[data-photo-index]').each(function(idx, obj) { if ($scope._use_lightBox) { $(this).attr('data-lightbox', 'view-gallery'); } else { $(this).attr('target', '_blank'); $(this).attr('data-nolightbox', 'true'); $(this).removeAttr('data-lightbox'); } }); } if ($scope.type === 'portfolio-carousel-boxed' && $scope.pageType == 'view_album_id') { $('.animateSlideFromRight').each(function(i, object) { if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function() { $(this).addClass('animateEnded').dequeue(); }); } }); return; } else if ($scope.type === 'portfolio-images-boxed') { $('.animteZoomToNormal').each(function(i, object) { if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function() { $(this).addClass('animateEnded').dequeue(); }); } }); return; } if ($('[data-iddd="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.slideInit(); }, 500); } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function() { var elementName = '[data-iddd="' + $scope._key() + '"]'; var optionsParmas = { autoplay: false, slidesToShow: 3, slidesToScroll: 3, dots: true, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [{ breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } }]; var extraOptions = { animate: false, slideFromRight: true, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } setTimeout(function() { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } }); }; $scope.getGridItemWidth = function() { return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx) { if ($scope._use_lightBox) { $('a[data-index="' + idx + '"]').attr('data-lightbox', 'gallery-view'); } else { $('a[data-index="' + idx + '"]').attr('data-nolightbox', 'yes'); } }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.setdispay = function(imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow', 'hidden'); } $scope.setdispayclose = function(imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow', 'visible'); } $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } }; return promise; });_ui_share_app.directive('componentAlbumIdA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentAlbumIdA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { col: '@col', margintopic: '@margintopic', margincard: '@margincard', albumid: '@albumid', albumname: '@albumname', limit: '@limit', sort: '@sort', console: '@console', empty: '@empty', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', 'topic_bottom': '?topicBottom', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._limit = parseInt((typeof $scope.limit !== 'undefined' && typeof $scope.limit !== '') ? $scope.limit : 6); $scope._sort = (typeof $scope.sort !== 'undefined' && typeof $scope.sort !== '') ? $scope.sort : 'image_group_sort_index_ASC'; $scope._console = Boolean((typeof $scope.console !== 'undefined' && typeof $scope.console !== '') ? $scope.console : false); $scope._empty = Boolean((typeof $scope.empty !== 'undefined' && typeof $scope.empty !== '') ? $scope.empty : false); $scope.viewRouteParams = function() { return $routeParams; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.$watch('col', function(newValue, oldValue) { if (newValue) { $scope._col = newValue.toString().split(","); } }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.showConsole = function(state, text, data) { if (state) { console.log(text, " : ", data); } }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.getImageGroup = function(cur, per, sort, id, console) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "gallery_id_array": [id] } var dataSend = { cur_page: cur, per_page: per, txt_sortby: sort, 'txt_filter_json': JSON.stringify(filter_json) }; $scope.showConsole(console, "getPhotoListByAlbumId dataSend", dataSend); GAEAPI.get('image_group/lists', dataSend, $scope).then(function(output) { $scope.showConsole(console, "getPhotoListByAlbumId output", output); if (output.ok == 1) { $scope.showConsole(console, "getPhotoListByAlbumId output OK", output); $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getImageGroup(1, $scope._limit, $scope._sort, $scope.albumid, $scope._console); }; return promise; });_ui_share_app.directive('componentAlbumImageSlide', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentAlbumImageSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', albumid: '@albumid', // position:'@position', // textstyle:'@textstyle', // buttonstyle:'@buttonstyle', // animatestyle:'@animatestyle', // margin:'@margin', // font:'@font', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'AlbumImageSlide'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; if(!carouselData.get($scope.type) && !$scope.data.length){ var jsonFilter = { 'image_group_id_array': [$scope.albumid] }; var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('image/lists', dataSend, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.dataList; if(resultArray.length){ carouselData.set($scope.type, resultArray); console.log("datatest1232",resultArray); $scope.data = resultArray; } else { $scope.done = true; return; } var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); }); } else { $scope.data = carouselData.get($scope.type); console.log("%ccarouselData => get state","background-color:yellow;color:black;padding:5px;"); var t = $interval(function () { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.initSlider(); }, 300); } }, 500); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, centerMode: true, centerPadding: '0px', slidesToShow: 3, slidesToScroll: 1, dots: false, arrows: false, infinite: true, draggable: false, swipe: false, responsive: [ { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 3 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 1 } } ] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.setdispay = function (imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow','hidden'); } $scope.setdispayclose = function (imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow','visible'); } $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ var a = i; if(a.indexOf('http') == -1){ return 'http://'+i; } return i; }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; }; return promise; }); /* component Alert to overide native javascript alert with HTML injection */ var $alertI = null; var $alertHTML = _ui_share_host+'componentAlert/componentAlert.html'; _ui_share_app.factory('$componentBadge', function componentBadge($routeParams, $timeout) { return });_ui_share_app.directive('componentBadgeId', function($rootScope, $routeParams) { var templateName = 'componentBadgeId'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', size: '@size', sizelist: '@sizelist', sort: '@sort', component: '@component', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.size = (typeof $scope.size !== 'undefined') ? $scope.size : 8; $scope.sizelist = (typeof $scope.sizelist !== 'undefined') ? $scope.sizelist : 4; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(badgeid) { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = { 'badge_id_array': [badgeid] }; var dataSend = { 'cur_page': 1, 'per_page': $scope.sizelist, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.badgeid); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentBadgeIdTypeA', function($rootScope, $routeParams) { var templateName = 'componentBadgeIdTypeA'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', limitdata: '@limitdata', col: '@col', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', view: '@view', currentData: '=data', // receive data from outside }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._viewproduct = ($scope.view == undefined || $scope.view == "") ? 'grid' : $scope.view; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.viewRouteParams = function() { return $routeParams; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "badge_id_array": [id] } var dataSend = { cur_page: 1, per_page: $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } if($scope.currentData != undefined && $scope.currentData){ $scope._dataArray = $scope.currentData; $scope._dataArrayState = $scope.StateData(false, true); } else { $scope._getDataArray($scope.badgeid); } }; return promise; });_ui_share_app.directive('componentBadgeIdTypeB', function($rootScope, $routeParams) { var templateName = 'componentBadgeIdTypeB'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', limitdata: '@limitdata', more: '@more', col: '@col', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', fontcolor: '@fontcolor', imgbutton: '@imgbutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = parseInt((typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 8); $scope._lmore = Boolean((typeof $scope.more !== 'undefined' && typeof $scope.more !== '') ? $scope.more : false); $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.viewRouteParams = function() { return $routeParams; }; $scope._dataArray = []; $scope.fetchTime = 1; $scope.moreShow = true; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "badge_id_array": [16,18,id] } var dataSend = { cur_page: $scope.fetchTime, per_page: $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; console.log("_getDataArray : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend , $scope).then(function(output) { console.log("_getDataArray : output : ", output); if (output.ok == 1) { if ($scope._dataArray.length) { var curData = $scope._dataArray; var total = output.data.total_rows; // $scope.$apply(function() { $scope._dataArray = curData.concat(output.data.dataList); $scope.showMore(total, $scope._dataArray.length); // }); } else { var curData = output.data.dataList; var total = output.data.total_rows; // $scope.$apply(function() { $scope._dataArray = output.data.dataList; $scope.showMore(total, $scope._dataArray.length); // }); } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.showMore = function(total, data) { if ($scope._lmore == true) { if (total <= data) { $scope.moreShow = false; } else { $scope.moreShow = true; } } else { $scope.moreShow = false; } } $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.badgeid); $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope._getDataArray($scope.badgeid); }, 300); }; }; return promise; });_ui_share_app.directive('componentBadgeIdTypeC', function($rootScope, $routeParams) { var templateName = 'componentBadgeIdTypeC'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', limitdata: '@limitdata', col: '@col', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 8; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.viewRouteParams = function() { return $routeParams; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "badge_id_array": [id] } var dataSend = { cur_page: 1, per_page: $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.badgeid); }; return promise; });_ui_share_app.directive('componentBadgeIdTypeD', function($rootScope, $routeParams) { var templateName = 'componentBadgeIdTypeD'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', limitdata: '@limitdata', col: '@col', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 8; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.viewRouteParams = function() { return $routeParams; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "badge_id_array": [id] } var dataSend = { cur_page: 1, per_page: $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.badgeid); }; return promise; });_ui_share_app.directive('componentBadgeIdTypeE', function($rootScope, $routeParams) { var templateName = 'componentBadgeIdTypeE'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', limitdata: '@limitdata', padding: '@padding', col: '@col', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', showhome: '@showhome', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._padding = ($scope.padding != undefined && $scope.padding != '') ? { padding: $scope.padding } : { padding: '0' }; $scope._showhome = ($scope.showhome == 'true' || $scope.showhome == 't') ? true : false; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 8; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.viewRouteParams = function() { return $routeParams; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var badge_array = []; if ($scope._showhome) { badge_array.push("16"); } if ($scope.badgeid != undefined && $scope.badgeid != "") { badge_array.push($scope.badgeid); } var filter_json = { "badge_id_array": badge_array } var dataSend = { cur_page: 1, per_page: $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.badgeid); }; return promise; });_ui_share_app.directive('componentBadgeSlideTypeA', function($rootScope, $routeParams) { var templateName = 'componentBadgeSlideTypeA'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', badgeid: '@badgeid', stylebutton: '@stylebutton', slideshow: '@slideshow', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop' }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.slideshow_all = $scope.slideshow ? $scope.slideshow : "3,3,2,1"; $scope._slideshow = $scope.slideshow_all.split(","); $scope._desktop_lg = $scope._slideshow[0]; $scope._desktop_md = $scope._slideshow[1]; $scope._desktop_sm = $scope._slideshow[2]; $scope._desktop_xs = $scope._slideshow[3]; $scope.key = ''; $scope.carouselKey = function() { if ($scope.key == '') { $scope.key = Math.floor((Math.random() * 9999) + 1000); return $scope.key; } else { return $scope.key; } }; $scope.carouselIn = function(elem) { $('.component-badge-slide-type-a').css('height', '0'); $('.component-badge-slide-type-a').css('opacity', '0'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope.carouselKey() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: $scope._desktop_lg, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: $scope._desktop_md, } }, { breakpoint: 991, settings: { slidesToShow: $scope._desktop_sm, } }, { breakpoint: 767, settings: { slidesToShow: $scope._desktop_xs, } }] }).closest('section').addClass('active'); $('.component-badge-slide-type-a').css('height', 'auto'); $('.component-badge-slide-type-a').css('opacity', '1'); }, 500); }; $scope.component = "componentBadgeSlideTypeA"; $scope.dataSet = [{ api: "product/lists", dataSend: {}, dataSendState: { load: false, done: false }, dataArray: [] }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); _self.consoleLog("stateData : loadIn : ", loadIn); _self.consoleLog("stateData : doneIn : ", doneIn); _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); var state = { load: loadIn, done: doneIn }; return state; }, routeParams: function(callback) { var params = $routeParams; callback(params); }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); _self.consoleLog("dataSend : api : ", api); _self.consoleLog("dataSend : dataSend : ", dataSend); _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); callback(api, dataSend); }, getApiOk: function(output, callback) { var _self = this; var output_ok = []; if (output.ok == 1) { output_ok = output; } _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); _self.consoleLog("getApiOk : output_ok : ", output_ok); _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); callback(output_ok); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getApi : api : ", api); _self.consoleLog("getApi : dataSend : ", dataSend); _self.consoleLog("getApi : output : ", output); _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.getApiOk(output, function(output) { callback(output); }); }); }, main: function() { var _self = this; _self.routeParams(function(params) { $scope.dataSet[0].dataSendState = _self.stateData(true, false); var filter_json = { "badge_id_array": [$scope.badgeid] } $scope.dataSet[0].dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_filter_json': JSON.stringify(filter_json) }; _self.dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { $scope.dataSet[0].dataArray = output.data.dataList; $scope.dataSet[0].dataSendState = _self.stateData(false, true); }); }); }); } } return getFunction; }; $scope.getFunction().main(); }; return promise; });_ui_share_app.directive('componentBadgeSlideTypeB', function($rootScope, $routeParams) { var templateName = 'componentBadgeSlideTypeB'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { data: '=', badgeid: '@badgeid', notreferralid: '@notreferralid', stylebutton: '@stylebutton', component: '@component', margin: '@margin', limitdata: '@limitdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.mkCarousel = function(elem) { $('.component-badge-slide-type-b .recommend').css('height', '0'); $('.component-badge-slide-type-b .recommend').css('opacity', '0'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, centerMode: false, infinite: false, variableWidth: false, autoplaySpeed: 4000, slidesToShow: 6, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 4, } }, { breakpoint: 992, settings: { slidesToShow: 3 } }, { breakpoint: 768, settings: { slidesToShow: 2 } }, { breakpoint: 480, settings: { slidesToShow: 2 } }] }).closest('section').addClass('active'); $('.component-badge-slide-type-b .recommend').css('height', 'auto'); $('.component-badge-slide-type-b .recommend').css('opacity', '1'); }, 1500); }; $scope.viewData = function() { var viewdata = 0; if ($(window).width() <= 480) { viewdata = 1; } else if ($(window).width() <= 768) { viewdata = 2; } else if ($(window).width() <= 992) { viewdata = 3; } else if ($(window).width() <= 1200) { viewdata = 4; } else { viewdata = 6; } return viewdata; }; $scope._productArray = []; $scope._productArrayDone = { load: true, done: false }; $scope._getProductArray = function(bid, notcid) { $scope._productArrayDone = { load: true, done: false }; $scope._productArray = []; var filter_json = { "badge_id_array": [bid] } var dataSend = { 'cur_page': 1, 'per_page': $scope.limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(res) { if (res.ok === 1) { console.log("watch badgeid", 'in 2'); $scope._productArray = res.data.dataList; } $scope._productArrayDone = { load: false, done: true }; }); }; $scope._getProductArray($scope.badgeid, $scope.notreferralid); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; });_ui_share_app.directive('componentBadgeSlideTypeC', function ($rootScope, $routeParams) { var templateName = 'componentBadgeSlideTypeC'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', limitdata: '@limitdata', iconsize: '@iconsize', iconnext: '@iconnext', iconback: '@iconback', }; promise.link = function (scope, element, attr) { }; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope.mkCarousel = function (elem) { setTimeout(function () { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { slidesToShow: 2, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getProductArray = function (id) { $scope._dataArrayState = { load: true, done: false }; var filter_json = { "badge_id_array": [id] } var dataSend = { 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function (res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; console.log("test121212 : ", $scope._dataArray); } $scope._dataArrayState = { load: false, done: true }; }); }; $scope.$watch('badgeid', function (newValue, oldValue) {             if (newValue) { // $setTimeout(function() { $scope._getProductArray(newValue); // }, 1000); } else { return; }         }); $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function () { setTimeout(function () { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function () { setTimeout(function () { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; });_ui_share_app.directive('componentBadgeSlideTypeD', function($rootScope, $routeParams) { var templateName = 'componentBadgeSlideTypeD'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { sortby: '@sortby', badgeid: '@badgeid', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', limitdata: '@limitdata', iconsize: '@iconsize', iconnext: '@iconnext', iconback: '@iconback', showresult: '@showresult', arrows: '@arrows', slidestoshowlarge: '@slidestoshowlarge', slidestoshowmedium: '@slidestoshowmedium', slidestoshowsmall: '@slidestoshowsmall', slidestoshowextrasmall: '@slidestoshowextrasmall', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._sortby = (typeof $scope.sortby !== 'undefined' && typeof $scope.sortby !== '') ? $scope.sortby : 'product_update_time_asc'; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope._showresult = (typeof $scope.showresult !== 'undefined' && typeof $scope.showresult !== '') ? $scope.showresult : true; $scope._arrows = (typeof $scope.arrows !== 'undefined' && typeof $scope.arrows !== '') ? ($scope.arrows == 'true') ? true : ($scope.arrows == 'false') ? false : false : false; $scope._iconsize = (typeof $scope.iconsize !== 'undefined' && typeof $scope.iconsize !== '') ? $scope.iconsize : 30; $scope._iconback = (typeof $scope.iconback !== 'undefined' && typeof $scope.iconback !== '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = (typeof $scope.iconnext !== 'undefined' && typeof $scope.iconnext !== '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope._slidestoshowlarge = parseInt((typeof $scope.slidestoshowlarge !== 'undefined' && typeof $scope.slidestoshowlarge !== '') ? $scope.slidestoshowlarge : 4); $scope._slidestoshowmedium = parseInt((typeof $scope.slidestoshowmedium !== 'undefined' && typeof $scope.slidestoshowmedium !== '') ? $scope.slidestoshowmedium : 3); $scope._slidestoshowsmall = parseInt((typeof $scope.slidestoshowsmall !== 'undefined' && typeof $scope.slidestoshowsmall !== '') ? $scope.slidestoshowsmall : 2); $scope._slidestoshowextrasmall = parseInt((typeof $scope.slidestoshowextrasmall !== 'undefined' && typeof $scope.slidestoshowextrasmall !== '') ? $scope.slidestoshowextrasmall : 1); $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function(id) { var in_id = id.split(","); $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "badge_id_array": in_id } var dataSend = { 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_sortby': $scope._sortby, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; } setTimeout(function() { $scope._dataArrayState = $scope.StateData(false, true); }, 100); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getProductArray($scope.badgeid); $scope.mkCarousel = function(elem) { $('.component-badge-slide-type-d').css('height', '0'); $('.component-badge-slide-type-d').css('opacity', '0'); console.log("mkCarousel : ", $scope._slidestoshowlarge, $scope._slidestoshowmedium, $scope._slidestoshowsmall, $scope._slidestoshowextrasmall); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: $scope._arrows, autoplay: true, centerMode: false, variableWidth: false, autoplaySpeed: 4000, slidesToShow: $scope._slidestoshowlarge, slidesToScroll: $scope._slidestoshowlarge, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: $scope._slidestoshowmedium, slidesToScroll: $scope._slidestoshowmedium, } }, { breakpoint: 991, settings: { slidesToShow: $scope._slidestoshowsmall, slidesToScroll: $scope._slidestoshowsmall, } }, { breakpoint: 767, settings: { slidesToShow: $scope._slidestoshowextrasmall, slidesToScroll: $scope._slidestoshowextrasmall, } }] }).closest('section').addClass('active'); $('.component-badge-slide-type-d').css('height', 'auto'); $('.component-badge-slide-type-d').css('opacity', '1'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; });_ui_share_app.directive('componentBadgeSlideTypeE', function($rootScope, $routeParams) { var templateName = 'componentBadgeSlideTypeE'; var componentMain = 'componentBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', padding: '@padding', badgeid: '@badgeid', showhome: '@showhome', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._padding = ($scope.padding != undefined && $scope.padding != '') ? { padding: $scope.padding } : { padding: '0' }; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._showhome = ($scope.showhome == 'true' || $scope.showhome == 't') ? true : false; $scope._component = "componentBadgeSlideTypeE"; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(_self, params, state); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carousel: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: true, arrows: false, infinite: false, autoplay: true, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 2, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 1, } }, { breakpoint: 991, settings: { slidesToShow: 3, slidesToScroll: 1, } }, { breakpoint: 767, settings: { slidesToShow: 2, slidesToScroll: 1, } }] }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, slickCarousel: function(carousel, index) { var _self = this; $scope.setCarousel.index = index; setTimeout(function() { $('[data-key="' + carousel + '"]').slick('slickGoTo', index); }, 100); } } return getFunction; }; $scope.setCarousel = { carousel: 0, index: 0 }; $scope.getCarousel().getCarousel($scope.setCarousel.carousel, function(res_carousel_id) { $scope.setCarousel.carousel = res_carousel_id; }); $scope.dataApi = { product: { data_send: {}, api: "product/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } }, }; $scope.getData().getRouteParams(function(_self, res_params, res_state) { $scope.dataApi.product.data_array_state = res_state; var badge_array = []; if ($scope._showhome) { badge_array.push("16"); } if ($scope.badgeid != undefined && $scope.badgeid != "") { badge_array.push($scope.badgeid); } var filter_json = { "badge_id_array": badge_array } var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'product_update_time_asc', 'txt_filter_json': JSON.stringify(filter_json) }; _self.consoleLog("getApiData dataSend", dataSend); $scope.dataApi.product.data_send = dataSend; _self.formatDataSend($scope.dataApi.product, function(res_data) { _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_dataSend) { _self.getApi(res_api, res_dataSend, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; res_data.data_array_state = res_state; _self.consoleLog("getApiData res_state", res_data); }); }) }); }); }; return promise; });_ui_share_app.factory('$componentBlog', function componentBlog($routeParams, $timeout) { return });_ui_share_app.directive('componentBlogIdTypeA', function($rootScope, $routeParams) { var templateName = 'componentBlogIdTypeA'; var componentMain = 'componentBlog'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { blogid: '@blogid', limitdata: '@limitdata', col: '@col', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.viewRouteParams = function() { return $routeParams; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "badge_id_array": [18], "blog_id_array": [id] } var dataSend = { cur_page: 1, per_page: $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('post/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.$watch('blogid', function(newValue, oldValue) {             if (newValue) { $scope._getDataArray(newValue); }               }); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentBlogHomeTypeA', function ($rootScope, $routeParams) { var templateName = 'componentBlogHomeTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', showbutton : '@showbutton', buttonstyle: '@buttonstyle', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.buttonstyleset = (typeof $scope.buttonstyle == 'undefined' || $scope.buttonstyle == '') ? "filled_button" : $scope.buttonstyle; $scope.bloglists = []; $scope.getbloglists = function(){ var dataSend = { 'cur_page':1, 'per_page':10, 'txt_sortby':'blog_lastest_create-z', }; GAEAPI.get('blog/lists',dataSend).then(function(e){ if(e.ok==1){ $scope.bloglists = e.data.dataList; } console.log('bloglists :',$scope.bloglists); }); }; $scope.getbloglists(); $scope.buildTitleUrl = function (str) { if(str != undefined){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; } }; $scope._blogArray = []; $scope._blogArrayDone = false; $scope._getBlogArray = function () { var filter_json = { 'badge_id_array': [16] } var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('post/lists', dataSend).then(function (res) { $scope._blogArrayDone = true; if (res.ok === 1) { $scope._blogArray = res.data.dataList; } else { $scope._blogArrayDone = true; } console.log('blogArray',$scope._blogArray); }); }; $scope._getBlogArray(); }; return promise; }); _ui_share_app.directive('componentBlogSlide', function($rootScope, $routeParams) { var templateName = 'componentBlogSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { isRender: '=', name: '@name', blogid: '@blogid', showbutton: '@showbutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarouselBlog = function(elem) { console.debug('mkCarouselBlog: trigger'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 2, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._blogArray = []; $scope._blogArrayDone = false; $scope._getBlogArray = function(blog_id) { $scope._blogArrayDone = false; $scope._blogArray = []; if (blog_id == null) { var filter_json = { 'badge_id_array': [16, 18] } } else { var filter_json = { 'badge_id_array': [16, 18], 'blog_id_array': [blog_id] } } console.log('filter_json_Blog', filter_json); var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Blog', dataSend); GAEAPI.get('post/lists', dataSend).then(function(res) { $scope._blogArrayDone = true; if (res.ok === 1) { $scope._blogArray = res.data.dataList; if (res.data.dataList.length > 0) { $scope.isRender = true; } else { $scope.isRender = false; } } else { $scope.isRender = false; $scope._blogArrayDone = true; } console.log('blogArray', $scope._blogArray); }); }; $scope._getBlogArray($scope.blogid); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } }; return promise; });_ui_share_app.directive('componentBlogTypeA', function ($rootScope, $routeParams) { var templateName = 'componentBlogTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', showbutton : '@showbutton', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.mkCarouselBlog = function (elem) { console.debug('mkCarouselBlog: trigger'); setTimeout(function () { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [ { breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 2, } }, { breakpoint: 767, settings: { slidesToShow: 1, } } ] }).closest('section').addClass('active'); }, 1000); }; $scope.bloglists = []; $scope.getbloglists = function(){ var dataSend = { 'cur_page':1, 'per_page':10, 'txt_sortby':'blog_lastest_create-z', }; GAEAPI.get('blog/lists',dataSend).then(function(e){ if(e.ok==1){ $scope.bloglists = e.data.dataList; } console.log('bloglists :',$scope.bloglists); }); }; $scope.getbloglists(); $scope._blogArray = []; $scope._blogArrayDone = false; $scope._getBlogArray = function () { var filter_json = { 'badge_id_array': [16,18] } var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('post/lists', dataSend).then(function (res) { $scope._blogArrayDone = true; if (res.ok === 1) { $scope._blogArray = res.data.dataList; } else { $scope._blogArrayDone = true; } console.log('blogArray',$scope._blogArray); }); }; $scope._getBlogArray(); $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function () { setTimeout(function () { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function () { setTimeout(function () { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; }); _ui_share_app.directive('componentBlogTypeB', function ($rootScope, $routeParams) { var templateName = 'componentBlogTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', showbutton : '@showbutton', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarouselBlog = function (elem) { console.debug('mkCarouselBlog: trigger'); setTimeout(function () { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [ { breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 2, } }, { breakpoint: 767, settings: { slidesToShow: 1, } } ] }).closest('section').addClass('active'); }, 1000); }; $scope._blogLists = []; $scope._getBlogLists = function () { var dataSend = { 'cur_page': 1, 'per_page': 7 }; GAEAPI.get('blog/lists', dataSend).then(function (res) { $scope._blogArrayDone = true; if (res.ok === 1) { $scope._blogLists = res.data.dataList; } console.log('_blogLists',$scope._blogLists); }); }; $scope._getBlogLists(); $scope._blogArray = []; $scope._blogArrayDone = false; $scope._getBlogArray = function (blog_id) { $scope._blogArrayDone = false; $scope._blogArray = []; if (blog_id == null) { var filter_json = { 'badge_id_array': [16,18] } } else{ var filter_json = { 'badge_id_array': [16,18], 'blog_id_array':[blog_id] } } console.log('filter_json_Blog',filter_json); var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Blog',dataSend); GAEAPI.get('post/lists', dataSend).then(function (res) { $scope._blogArrayDone = true; if (res.ok === 1) { $scope._blogArray = res.data.dataList; } else { $scope._blogArrayDone = true; } console.log('blogArray',$scope._blogArray); }); }; $scope._getBlogArray(); $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function () { setTimeout(function () { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function () { setTimeout(function () { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function (evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } }; return promise; }); _ui_share_app.directive('componentBlogTypeC', function($rootScope, $routeParams) { var templateName = 'componentBlogTypeC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { isRender: '=', name: '@name', showbutton: '@showbutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarouselBlog = function(elem) { console.debug('mkCarouselBlog: trigger'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 2, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._blogLists = []; $scope._getBlogLists = function() { var dataSend = { 'cur_page': 1, 'per_page': 7 }; GAEAPI.get('blog/lists', dataSend).then(function(res) { $scope._blogArrayDone = true; if (res.ok === 1) { $scope._blogLists = res.data.dataList; } console.log('_blogLists', $scope._blogLists); }); }; $scope._getBlogLists(); $scope._blogArray = []; var length_return = 0; $scope._getBlogArray = function(blog_id) { if (blog_id == null) { var filter_json = { 'badge_id_array': [16, 18] } } else { var filter_json = { 'badge_id_array': [16, 18], 'blog_id_array': [blog_id] } } console.log('filter_json_Blog', filter_json); var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Blog', dataSend); GAEAPI.get('post/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._blogArray = res.data.dataList; console.log('blogArray', $scope._blogArray.length); } }); }; /*$scope._getBlogArray();*/ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } }; return promise; });_ui_share_app.directive('componentBlogTypeD', function($rootScope, $routeParams) { var templateName = 'componentBlogTypeD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'cover_top': '?coverTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window, $location) { $scope._component = "componentBlogTypeD"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { console.log($scope._component, ' : ', functionName, ' : ', data); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, lifetime: function(postLifetime) { var now = moment().unix(); return (postLifetime.lifetime_start_time <= now && (postLifetime.lifetime_end_time == -1 || now <= postLifetime.lifetime_end_time)) ? true : false; }, main: function() { var _self = this; } } return getFunction; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* post */ $scope.setData = { dataSend: {}, api: "post/lists", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }; /* post */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.setData.dataArrayState = res_state; /* var txt_filter_json = { "badge_id_array": [16, 18], "blog_id_array": [blog_id] }; */ var txt_filter_json = { "badge_id_array": [16, 18] }; $scope.setData.dataSend.cur_page = 1; $scope.setData.dataSend.per_page = 50; $scope.setData.dataSend.txt_filter_json = JSON.stringify(txt_filter_json); $scope.getData().dataSend($scope.setData.api, $scope.setData.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api, res_state) { $scope.setData.ok = res_ok; angular.forEach(get_res_api.data.dataList, function(item, key) { if ($scope.getData().lifetime(item.post_lifetime)) { console.log("forEach : item : post_lifetime : ", item.post_lifetime); $scope.setData.dataArray.push(item); } }); $scope.setData.dataArrayState = res_state; }); }); }); }; return promise; });_ui_share_app.directive('componentBlogTypeE', function($rootScope, $routeParams) { var templateName = 'componentBlogTypeE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', sortby: '@sortby', feature: '@feature', padding: '@padding', blogid: '@blogid', bloglimit: '@bloglimit', size: '@size', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.useFeature = (typeof $scope.feature !== 'undefined' && $scope.feature != '') ? true : false; /**/ $scope._bloglimit = ($scope.bloglimit != '' && $scope.bloglimit != undefined) ? parseInt($scope.bloglimit) : 10; /**/ $scope.typelist = []; $scope.getTypeList = function() { GAEAPI.get('blog/lists', { 'cur_page': 1, 'per_page': $scope._bloglimit }, $scope).then(function(e) { if (e.ok == 1) { $scope.typelist = e.data.dataList; } }); }; $scope.getTypeList(); /**/ /**/ $scope._blogArray = []; $scope._blogArrayDone = false; $scope._getBlogArray = function(filter) { var data_Id = filter.id; var data_blogid = $scope.blogid; console.log('data_Id', data_Id); if (data_Id == undefined) { if (data_blogid == undefined) { var txt_filter_json = { "badge_id_array": [16, 18] }; } else { var txt_filter_json = { "badge_id_array": [18], "blog_id_array": [data_blogid] }; } } else { var txt_filter_json = { "badge_id_array": [16, 18], "blog_id_array": [data_Id] }; } var dataSend = { 'cur_page': 1, 'per_page': 50, 'txt_sortby': (typeof $scope.sortby !== 'undefined' && $scope.sortby !== '') ? $scope.sortby : 'post_update_time_DESC', 'txt_filter_json': JSON.stringify(txt_filter_json) }; console.log("dataSend dataSend dataSend", dataSend); GAEAPI.get('post/lists', dataSend).then(function(res) { $scope._blogArrayDone = true; if (res.ok === 1) { $scope._blogArray = res.data.dataList; } else { $scope._blogArrayDone = true; } console.log('blogArray', $scope._blogArray); }); }; $scope._getBlogArray($routeParams); /**/ /**/ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.viewRouteParams = function() { return $routeParams; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._makeDate = function(dateStr) { return (dateStr != "") ? moment(parseInt(dateStr) * 1000).format('LL') : ""; }; }; return promise; });_ui_share_app.directive('componentBlogTypeF', function($rootScope, $routeParams) { var templateName = 'componentBlogTypeF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._blogArray = []; $scope._getBlogArray = function() { var filter_json = { 'badge_id_array': [16, 18] } var dataSend = { 'cur_page': 1, 'per_page': 5, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('post/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._blogArray = res.data.dataList; console.log('blogArray', $scope._blogArray.length); } }); }; $scope._getBlogArray(); $scope._makeDate = function(dateStr){ return (dateStr!="") ? moment(parseInt(dateStr) * 1000).format('LL') : ""; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; });_ui_share_app.directive('componentBlogTypeSk', function($rootScope, $routeParams, $location) { var templateName = 'componentBlogTypeSk'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope._component = { name: "componentBlogTypeSk", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._margin = ($scope.margin != undefined && $scope.margin != "") ? { margin: $scope.margin } : { margin: 0 }; $scope._limit = ($scope.limit != undefined && $scope.limit != "") ? parseInt($scope.limit) : 1; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getBlogId: function(params, callback) { var _self = this; var blog_id = (params.blog_id != undefined) ? params.blog_id.split("-", 1).join("") : false; _self.consoleLog("getBlogId", "blog_id", blog_id); callback(blog_id); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, getDate: function(locale, format, lifetime, callback) { var _self = this; locale = (locale == '') ? 'en' : locale; format = (format == '') ? 'LL' : format; lifetime = (lifetime != "-1" && lifetime != "") ? lifetime : ""; if (lifetime != "") { moment.locale(locale); lifetime = moment.unix(parseInt(lifetime)).format(format); } _self.consoleLog("getDate", "lifetime", lifetime); callback(lifetime); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, getCur: function(index, total, show, start, end, callback) { var _self = this; if (index == 1 && total > show) { end = show; } else if (index == total && total > show) { start = total - (show - 1); } else if (index < show && index <= (show / 2) && total > show) { end = show; } else if (index > (show / 2) && (index + (show / 2)) <= total && total > show) { start = (index - ((show / 2) - 1)); end = (index + ((show / 2))); } else if (index < total && total > show) { start = total - (show - 1); } _self.getCurArray(start, end, function(res_cur_page_array) { _self.consoleLog("getCur", "res_cur_page_array", res_cur_page_array); callback(res_cur_page_array); }); }, getCurArray: function(start, end, callback) { var _self = this; var cur_page_array = []; for (var i = start; i <= end; i++) { var item = { state: true, number: i } cur_page_array.push(item); } _self.consoleLog("getCurArray", "cur_page_array", cur_page_array); callback(cur_page_array); }, getCurPageArray: function(curPage, perPage, totalRows, callback) { var _self = this; var show = 6; var cur_pages = Math.round(totalRows / perPage); var cur_page_array = []; var cur = { start: 1, end: cur_pages } _self.getCur(curPage, cur_pages, show, cur.start, cur.end, function(res_cur_page_array) { cur_page_array = res_cur_page_array; }); _self.consoleLog("getCurPageArray", "cur_page_array", cur_page_array); callback(cur_page_array); }, main: function() { var _self = this; } } return getFunction; }; $scope.getPages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageBlog: function(page_name, blog_id, blog_name_url) { var _self = this; var page = page_name; page = (blog_id == '' || blog_name_url == '') ? page : page + "/" + blog_id + "-" + blog_name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.getCur = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getLeft: function() { var _self = this; var index = ($scope.data_api.load_more.cur_page - 1 != 0) ? $scope.data_api.load_more.cur_page - 1 : false; _self.consoleLog("getLeft", "index", index); if (index != false) { $scope.loadPage(index); } }, getRight: function() { var _self = this; var _self = this; var cur_pages = Math.round($scope.data_api.load_more.total_rows / $scope.data_api.load_more.per_page); var index = ($scope.data_api.load_more.cur_page + 1 < cur_pages) ? $scope.data_api.load_more.cur_page + 1 : false; _self.consoleLog("getRight", "index", index); if (index != false) { $scope.loadPage(index); } }, } return getFunction; }; /* get api */ $scope.data_api = { blog_id: false, load_more: { load: false, cur_page: 1, cur_page_array: [], per_page: 9, total_rows: 0 }, blog: { data_send: {}, api: "blog/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } }, post: { data_send: {}, api: "post/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.loadMore = function() { if (!$scope.data_api.load_more.load) { $scope.data_api.load_more.cur_page++; $scope.data_api.load_more.load = true; $scope.getData().getRouteParams(function(_self, params, state) { _self.getBlogId(params, function(res_blog_id) { _self.formatDataSend($scope.data_api.post, function(res_data) { var filter_json = {}; filter_json.lifetime_enable = 1; filter_json.blog_id_array = (res_blog_id != false) ? [res_blog_id] : []; var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'post_create_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var oldData = res_data.data_array; res_data.data_array = oldData.concat(res_api.data.dataList); angular.forEach(res_data.data_array, function(item, index) { _self.getDate('en', 'LL', res_data.data_array[index].post_create_time, function(res_lifetime) { res_data.data_array[index].post_create_time_en = res_lifetime; }); _self.getDate('en', 'LL', res_data.data_array[index].post_lifetime.lifetime_start_time, function(res_lifetime) { res_data.data_array[index].post_lifetime.lifetime_start_time_en = res_lifetime; }); _self.getDate('en', 'LL', res_data.data_array[index].post_lifetime.lifetime_end_time, function(res_lifetime) { res_data.data_array[index].post_lifetime.lifetime_end_time_en = res_lifetime; }); _self.getNameUrl(res_data.data_array[index].post_title, function(res_title) { res_data.data_array[index].post_title_url = res_title; }); }); $scope.data_api.load_more.total_rows = res_api.data.total_rows; } else { $scope.data_api.load_more.cur_page--; } $scope.data_api.load_more.load = false; }); }); }); }); }); } } $scope.loadPage = function(index) { $scope.data_api.post = { data_send: {}, api: "post/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } } $scope.data_api.load_more.cur_page = parseInt(index); $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.post.data_array_state = state; _self.getBlogId(params, function(res_blog_id) { _self.formatDataSend($scope.data_api.post, function(res_data) { var filter_json = {}; filter_json.lifetime_enable = 1; filter_json.blog_id_array = (res_blog_id != false) ? [res_blog_id] : []; $scope.data_api.blog_id = (res_blog_id == false) ? res_blog_id : res_blog_id; var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'post_update_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getDate('en', 'LL', res_data.data_array[index].post_create_time, function(res_lifetime) { res_data.data_array[index].post_create_time_en = res_lifetime; }); _self.getDate('en', 'LL', res_data.data_array[index].post_lifetime.lifetime_start_time, function(res_lifetime) { res_data.data_array[index].post_lifetime.lifetime_start_time_en = res_lifetime; }); _self.getDate('en', 'LL', res_data.data_array[index].post_lifetime.lifetime_end_time, function(res_lifetime) { res_data.data_array[index].post_lifetime.lifetime_end_time_en = res_lifetime; }); _self.getNameUrl(res_data.data_array[index].post_title, function(res_title) { res_data.data_array[index].post_title_url = res_title; }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; _self.getCurPageArray($scope.data_api.load_more.cur_page, $scope.data_api.load_more.per_page, res_api.data.total_rows, function(res_cur_page_array) { $scope.data_api.load_more.cur_page_array = res_cur_page_array; }); }); }); }); }); }); }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.blog.data_array_state = state; _self.formatDataSend($scope.data_api.blog, function(res_data) { var filter_json = {}; var dataSend = { 'cur_page': 1, 'per_page': 6, 'txt_sortby': 'blog_oldest_create', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getNameUrl(res_data.data_array[index].blog_name, function(res_name) { res_data.data_array[index].blog_name_url = res_name; }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); $scope.data_api.post.data_array_state = state; _self.getBlogId(params, function(res_blog_id) { _self.formatDataSend($scope.data_api.post, function(res_data) { var filter_json = {}; filter_json.lifetime_enable = 1; filter_json.blog_id_array = (res_blog_id != false) ? [res_blog_id] : []; $scope.data_api.blog_id = (res_blog_id == false) ? res_blog_id : res_blog_id; var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'post_update_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getDate('en', 'LL', res_data.data_array[index].post_create_time, function(res_lifetime) { res_data.data_array[index].post_create_time_en = res_lifetime; }); _self.getDate('en', 'LL', res_data.data_array[index].post_lifetime.lifetime_start_time, function(res_lifetime) { res_data.data_array[index].post_lifetime.lifetime_start_time_en = res_lifetime; }); _self.getDate('en', 'LL', res_data.data_array[index].post_lifetime.lifetime_end_time, function(res_lifetime) { res_data.data_array[index].post_lifetime.lifetime_end_time_en = res_lifetime; }); _self.getNameUrl(res_data.data_array[index].post_title, function(res_title) { res_data.data_array[index].post_title_url = res_title; }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; _self.getCurPageArray($scope.data_api.load_more.cur_page, $scope.data_api.load_more.per_page, res_api.data.total_rows, function(res_cur_page_array) { $scope.data_api.load_more.cur_page_array = res_cur_page_array; }); }); }); }); }); }); /* get api */ }; return promise; });_ui_share_app.directive('componentBlogTypeStyle', function($rootScope, $routeParams, $location) { var templateName = 'componentBlogTypeStyle'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, getBlogId: function(params, callback) { try { var blog_id = params.blog_id.split("-", 1).join(""); callback(blog_id) } catch (err) { var blog_id = 0; callback(blog_id) } }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, loopApi: function(cur_page, total_rows, total_data_array) { var _self = this; if (total_data_array < total_rows) { _self.getRouteParams(function(params) { _self.getBlogId(params, function(blog_id) { var loop_cur_page = cur_page + 1 var filter_json = { 'badge_id_array': [18] } if (blog_id != 0) { filter_json.blog_id_array = [blog_id] } $scope.dataSet[1].dataSend = { 'cur_page': loop_cur_page, 'per_page': $scope.dataMore.per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) } $scope.getData().dataSend($scope.dataSet[1].api, $scope.dataSet[1].dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.total.dataArray.push(output.data.dataList); $scope.total.total_data_array = $scope.total.total_data_array + output.data.dataList.length; if ($scope.total.total_data_array < output.data.total_rows) { _self.loopApi(loop_cur_page, output.data.total_rows, output.data.dataList.length); } }); }); }); }); } }, lifetime: function(postLifetime) { var now = moment().unix(); return (postLifetime.lifetime_start_time <= now && (postLifetime.lifetime_end_time == -1 || now <= postLifetime.lifetime_end_time)) ? true : false; }, more: function() { var _self = this; var cur_page = $scope.dataMore.cur_page - 1; $scope.dataMore.state = true; if ($scope.dataMore.cur_page <= $scope.total.dataArray.length) { $scope.dataMore.cur_page++; var oldData = $scope.dataArray; $scope.dataArray = oldData.concat($scope.total.dataArray[cur_page]); $scope.dataMore.state = false; if ($scope.dataArray.data.dataList.length < $scope.total.total_rows) { $scope.dataMore.show = true; } else { $scope.dataMore.show = false; } } else { setTimeout(function() { _self.more(); }, 1000); } }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrlBlog: function(blog_id, blog_title) { var _self = this; var url = 'blog/'; url += blog_id + '-'; url += _self.titleUrl(blog_title); _self.locationUrl(url, ''); }, locationUrlBlogDetail: function(post_id, post_title) { var _self = this; var url = 'blog-detail/'; url += post_id + '-'; url += _self.titleUrl(post_title); _self.locationUrl(url, ''); }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.makeDate = function(dateStr) { return (dateStr != "") ? moment(parseInt(dateStr) * 1000).format('LL') : ""; }; $scope.dataSet = [{ api: "blog/lists", dataSend: {} }, { api: "post/lists", dataSend: {} }]; $scope.blogId = '0'; $scope.dataTopArray = []; $scope.dataTopArray = []; $scope.dataTopArrayState = { load: false, done: false }; $scope.dataMore = { state: false, show: false, cur_page: 1, per_page: 30 }; $scope.dataArray = []; $scope.total = { dataArray: [], total_rows: 0, total_data_array: 0 }; $scope.getData().getRouteParams(function(params) { $scope.getData().consoleLog("getData : getRouteParams : params : ", params); $scope.getData().getBlogId(params, function(blog_id) { $scope.getData().consoleLog("getData : getBlogId : blog_id : ", blog_id); $scope.blogId = blog_id.toString(); var filter_json = {} $scope.dataSet[0].dataSend = { 'cur_page': 1, 'per_page': 10, 'txt_sortby': 'blog_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) } $scope.getData().dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.getData().consoleLog("getData : dataSend : getApi : output : ", output); $scope.dataTopArray = output; }); }); }); }); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); $scope.getData().consoleLog("getData : getRouteParams : params : ", params); $scope.getData().getBlogId(params, function(blog_id) { $scope.getData().consoleLog("getData : getBlogId : blog_id : ", blog_id); var filter_json = { 'badge_id_array': [18] } if (blog_id != 0) { filter_json.blog_id_array = [blog_id] } $scope.dataSet[1].dataSend = { 'cur_page': $scope.dataMore.cur_page, 'per_page': $scope.dataMore.per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) } $scope.getData().dataSend($scope.dataSet[1].api, $scope.dataSet[1].dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { angular.forEach(output.data.dataList, function(item, key) { if ($scope.getData().lifetime(item.post_lifetime)) { console.log("forEach : item : post_lifetime : ", item.post_lifetime); $scope.dataArray.push(item); } }); $scope.dataArrayState = $scope.getData().stateData(false, true); // $scope.getData().consoleLog("getData : dataSend : getApi : $scope.dataArray : ", $scope.dataArray); // $scope.total.total_rows = output.data.total_rows; // $scope.total.total_data_array = output.data.dataList.length; // if ($scope.dataArray.length < $scope.total.total_rows) { // $scope.dataMore.show = true; // } else { // $scope.dataMore.show = false; // } // $scope.getData().loopApi($scope.dataMore.cur_page, $scope.total.total_rows, $scope.total.total_data_array); }); }); }); }); }; return promise; });_ui_share_app.directive('componentBottomA', function ($rootScope, $routeParams) { var templateName = 'componentBottomA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.directive('componentBranchDetail', function($rootScope, $routeParams) { var templateName = 'componentBranchDetail'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', branchid: '@branchid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; if ($scope.branchid != "" || $scope.branchid != undefined) { $scope.branchDetail = parseInt($scope.branchid); } else { $scope.branchDetail = parseInt(0); } $scope.branchListIdDetail = []; $scope.getBranchDetail = function() { var dataSend = { 'txt_shop_branch_id': $scope.branchDetail }; GAEAPI.get('shop_branch/id', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branchListIdDetail = res.data; console.log("shop_branch", res); } else { console.log("shop_branch", res); } }); } $scope.getBranchDetail(); $scope.getOpenTableFromGoogle = function(item) { var r = []; var e = 'https://maps.google.com/maps/api/geocode/json?address='; /*$http.get(e+item.branch_location_title).then(function(res){ console.log("getOpenTableFromGoogle",res.data); });*/ }; $scope.makeDummy = function() { var o = function(i) { return { 'branch_id': i, 'branch_name': 'บริษัท เอ็กซ์-สปีด กรุ๊ป จำกัด', 'branch_phone': '02-979-5965-66', 'branch_mobile': '087-9999653', 'branch_description': 'สำนักงานใหญ่ detail', 'branch_short_description': 'สำนักงานใหญ่', 'branch_location_title': 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000', 'branch_location_latitude': '13.994813', 'branch_location_longtitude': '100.564529', 'branch_workingtime_array': [{ 'txt_index': 1, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, { 'txt_index': 2, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 3, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 4, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 5, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 6, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 7, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, ], 'branch_image': [{ 'image_url': 'https://image.getappeasy.com/src/images/2000/1032/0033/32033t1496650984.jpg' }] }; } var r = [o(1)]; $scope.getOpenTableFromGoogle(r[0]); return r; }; if ($scope.data.length <= 0) { $scope.getData(); } $scope.displayDayByIndex = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.buildIframeMapByLocline = function(name, lat, lng) { var newName = name; // if (/\s/.test(name)) { // var newNameOld = name.split(" "); // var DataName = newNameOld.join("+"); // } // var srcByName = 'https://www.google.co.th/maps?q=' + DataName; // var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; // return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName + '&output=embed&hl=th-TH'; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return srcByLoc; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.displayTelCode = function(telString) { console.log("displayTelCode : telString : ", telString); if (telString == undefined) { return 0; } else { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } /* if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); */ }; }; return promise; });_ui_share_app.directive('componentBranchDetailA', function($rootScope, $routeParams) { var templateName = 'componentBranchDetailA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', branchid: '@branchid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $http) { $scope.data = []; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.$watch('branchid', function(newValue, oldValue) { if (!newValue) { return; } $scope._getBlogArray(); }); if ($scope.branchid != "" || $scope.branchid != undefined) { $scope.branchDetail = parseInt($scope.branchid); } else { $scope.branchDetail = parseInt(0); } $scope.branchListIdDetail = []; $scope.getBranchDetail = function() { var dataSend = { 'txt_shop_branch_id': $scope.branchDetail }; GAEAPI.get('shop_branch/id', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branchListIdDetail = res.data; console.log("shop_branch", res); } else { console.log("shop_branch", res); } }); } $scope.getBranchDetail(); $scope.getOpenTableFromGoogle = function(item) { var r = []; var e = 'https://maps.google.com/maps/api/geocode/json?address='; /*$http.get(e+item.branch_location_title).then(function(res){ console.log("getOpenTableFromGoogle",res.data); });*/ }; $scope.makeDummy = function() { var o = function(i) { return { 'branch_id': i, 'branch_name': 'บริษัท เอ็กซ์-สปีด กรุ๊ป จำกัด', 'branch_phone': '02-979-5965-66', 'branch_mobile': '087-9999653', 'branch_description': 'สำนักงานใหญ่ detail', 'branch_short_description': 'สำนักงานใหญ่', 'branch_location_title': 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000', 'branch_location_latitude': '13.994813', 'branch_location_longtitude': '100.564529', 'branch_workingtime_array': [{ 'txt_index': 1, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, { 'txt_index': 2, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 3, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 4, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 5, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 6, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 7, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, ], 'branch_image': [{ 'image_url': 'https://image.getappeasy.com/src/images/2000/1032/0033/32033t1496650984.jpg' }] }; } var r = [o(1)]; $scope.getOpenTableFromGoogle(r[0]); return r; }; if ($scope.data.length <= 0) { $scope.getData(); } $scope.displayDayByIndex = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.buildIframeMapByLoc = function(itemObj) { var locJsonSearch = 'http://maps.google.com/maps/api/geocode/json?address='; var key = 'AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18'; var title = itemObj.shop_branch_name; var location = itemObj.shop_branch_map_location_array[0].name.split(" "); var locationSearch = location.join('+'); var lat = itemObj.shop_branch_map_location_array[0].lat; var lng = itemObj.shop_branch_map_location_array[0].lng; var srcByName = 'https://www.google.co.th/maps?q=' + title + ',' + locationSearch + '&output=embed&hl=th-TH'; /*var srcByLoc = 'https://www.google.com/maps/embed/v1/place?key='+key+'&q='+title+',' + locationSearch;*/ var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('componentBranchDetailB', function($rootScope, $routeParams) { var templateName = 'componentBranchDetailB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', branchid: '@branchid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $http) { $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.data = []; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.$watch('branchid', function(newValue, oldValue) { if (!newValue) { return; } }); if ($scope.branchid != "" || $scope.branchid != undefined) { $scope.branchDetail = parseInt($scope.branchid); } else { $scope.branchDetail = parseInt(0); } $scope.branchListIdDetail = []; $scope.getBranchDetail = function() { var dataSend = { 'txt_shop_branch_id': $scope.branchDetail }; GAEAPI.get('shop_branch/id', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branchListIdDetail = res.data; var a = $interval(function() { if ($scope._uniqueKey != '') { $interval.cancel(a); $scope.mkCarouselTwo(); } }, 1000); console.log("shop_branch", res); } else { console.log("shop_branch", res); } }); } $scope.getBranchDetail(); $scope.getOpenTableFromGoogle = function(item) { var r = []; var e = 'https://maps.google.com/maps/api/geocode/json?address='; /*$http.get(e+item.branch_location_title).then(function(res){ console.log("getOpenTableFromGoogle",res.data); });*/ }; $scope.makeDummy = function() { var o = function(i) { return { 'branch_id': i, 'branch_name': 'บริษัท เอ็กซ์-สปีด กรุ๊ป จำกัด', 'branch_phone': '02-979-5965-66', 'branch_mobile': '087-9999653', 'branch_description': 'สำนักงานใหญ่ detail', 'branch_short_description': 'สำนักงานใหญ่', 'branch_location_title': 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000', 'branch_location_latitude': '13.994813', 'branch_location_longtitude': '100.564529', 'branch_workingtime_array': [{ 'txt_index': 1, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, { 'txt_index': 2, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 3, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 4, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 5, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 6, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 7, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, ], 'branch_image': [{ 'image_url': 'https://image.getappeasy.com/src/images/2000/1032/0033/32033t1496650984.jpg' }] }; } var r = [o(1)]; $scope.getOpenTableFromGoogle(r[0]); return r; }; if ($scope.data.length <= 0) { $scope.getData(); } $scope.displayDayByIndex = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.buildIframeMapByNaneLoc = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps/embed/v1/place?key=AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18&q=' + DataName; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; $scope.mkCarouselTwo = function() { $('.text_slider_container[data-id=' + $scope._key() + ']').not('.slick-initialized').slick({ /* dots: true,*/ autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }).closest('section').addClass('active'); }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('componentBranchList', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBranchList'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.branchList = []; $scope.getBranchList = function() { var dataSend = { 'cur_page': 1, 'per_page': 100 }; GAEAPI.get('shop_branch/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branchList = res.data.dataList; console.log("utredsgajkhj", $scope.branchList); } }); } $scope.getBranchList(); $scope.makeDummy = function() { var o = function(i) { return { 'branch_id': i, 'branch_name': 'บริษัท เอ็กซ์-สปีด กรุ๊ป จำกัด', 'branch_phone': '02-979-5965-66', 'branch_mobile': '087-9999653', 'branch_description': 'สำนักงานใหญ่ detail', 'branch_short_description': 'สำนักงานใหญ่', 'branch_location_title': 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000', 'branch_location_latitude': '0', 'branch_location_longtitude': '0', 'branch_workingtime_array': [{ 'txt_index': 1, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, { 'txt_index': 2, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 3, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 4, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 5, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 6, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 7, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, ], 'branch_image': [{ 'image_url': 'https://image.getappeasy.com/src/images/2000/1032/0033/32033t1496650984.jpg' }] }; } var r = [o(1)]; return r; }; if ($scope.data.length <= 0) { $scope.getData(); } /*if ($scope.branchListTest.length <= 0) { $scope.getBrandList(); }*/ $scope.displayDayByIndex = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.mapQueryString = function() { var a = 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000'; var b = 'https://www.google.co.th/maps?q=' + a.split(' ').join('+') + '&output=embed'; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildLinkPhoneByTxt = function(str) {}; $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; }; return promise; });_ui_share_app.directive('componentBranchListB', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBranchListB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.branchList = []; $scope.getBranchList = function() { var dataSend = { 'cur_page': 1, 'per_page': 100 }; GAEAPI.get('shop_branch/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branchList = res.data.dataList; console.log("utredsgajkhj", $scope.branchList); } }); } $scope.getBranchList(); $scope.makeDummy = function() { var o = function(i) { return { 'branch_id': i, 'branch_name': 'บริษัท เอ็กซ์-สปีด กรุ๊ป จำกัด', 'branch_phone': '02-979-5965-66', 'branch_mobile': '087-9999653', 'branch_description': 'สำนักงานใหญ่ detail', 'branch_short_description': 'สำนักงานใหญ่', 'branch_location_title': 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000', 'branch_location_latitude': '0', 'branch_location_longtitude': '0', 'branch_workingtime_array': [{ 'txt_index': 1, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, { 'txt_index': 2, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 3, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 4, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 5, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 6, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 7, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, ], 'branch_image': [{ 'image_url': 'https://image.getappeasy.com/src/images/2000/1032/0033/32033t1496650984.jpg' }] }; } var r = [o(1)]; return r; }; if ($scope.data.length <= 0) { $scope.getData(); } /*if ($scope.branchListTest.length <= 0) { $scope.getBrandList(); }*/ $scope.displayDayByIndex = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.mapQueryString = function() { var a = 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000'; var b = 'https://www.google.co.th/maps?q=' + a.split(' ').join('+') + '&output=embed'; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildLinkPhoneByTxt = function(str) {}; $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.buildIframeMapByLoc = function(itemObj) { var locJsonSearch = 'http://maps.google.com/maps/api/geocode/json?address='; var key = 'AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18'; var title = itemObj.shop_branch_name; var location = itemObj.shop_branch_map_location_array[0].name.split(" "); var locationSearch = location.join('+'); var lat = itemObj.shop_branch_map_location_array[0].lat; var lng = itemObj.shop_branch_map_location_array[0].lng; var srcByName = 'https://www.google.co.th/maps?q=' + title + ',' + locationSearch + '&output=embed&hl=th-TH'; /*var srcByLoc = 'https://www.google.com/maps/embed/v1/place?key='+key+'&q='+title+',' + locationSearch;*/ var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; }; return promise; });_ui_share_app.directive('componentBrandSlide', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBrandSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', position:'@position', textstyle:'@textstyle', buttonstyle:'@buttonstyle', animatestyle:'@animatestyle', margin:'@margin', font:'@font', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.ref_id = $routeParams.referral_id; $scope.relate_name = $routeParams.referral_relate_name; $scope.brand_id = $routeParams.brand_id; /* referral_relate_name*/ $scope.type = 'BrandSlide'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; if(!carouselData.get($scope.type) && !$scope.data.length){ var dataSend = { 'txt_referral_type_id': 12, 'cur_page':1, 'per_page':10, 'txt_sortby':'referral_lastest_create' }; GAEAPI.get('referral/lists', dataSend, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.dataList; if(resultArray.length){ carouselData.set($scope.type, resultArray); console.log("datatest1232",resultArray); $scope.data = resultArray; } else { $scope.done = true; return; } var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); }); } else { $scope.data = carouselData.get($scope.type); console.log("%ccarouselData => get state","background-color:yellow;color:black;padding:5px;"); var t = $interval(function () { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.initSlider(); }, 300); } }, 500); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 4, slidesToScroll: 1, dots: false, arrows: true, infinite: true, responsive: [ { breakpoint: 768, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } } ] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ var a = i; if(a.indexOf('http') == -1){ return 'http://'+i; } return i; }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Check if child array exist */ $scope.checkChild = function(object){ return (!object.referral_sub_array.length) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentBrandTypeA', function ($rootScope, $routeParams) { var templateName = 'componentBrandTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', imgpath: '@imgpath', name: '@name', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ }; $scope.getData(); $scope.brandListGroup = []; $scope.brandList = []; $scope.getBrandList = function() { var dataSend = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 1000, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.brandList = res.data.dataList; if ($scope.brandList.length > 0) { var fisrtChar = ''; var headArr = []; var headResult = {}; angular.forEach($scope.brandList, function(v, k) { fisrtChar = v.referral_name.substring(0, 1); if (!headResult.hasOwnProperty(fisrtChar)) { headResult[fisrtChar] = []; headResult[fisrtChar].push(v); } else { headResult[fisrtChar].push(v); } }); $scope.brandListGroup = headResult; } } }); } $scope.getBrandList(); }; return promise; }); _ui_share_app.directive('componentBrandTypeB', function($rootScope, $routeParams) { var templateName = 'componentBrandTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading: '@heading', type: '@type', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataArray = []; $scope.dataArrayState = { load: false, done: false }; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, imageUrl: function(size, image_url) { var url = image_url.split("/"), length_url = url[url.length - 1]; url[url.length - 1] = size + '_' + length_url; return url.join("/"); }, resizeImageUrl: function(output, callback) { var _self = this; for (var i = 0; i <= output.length; i++) { if (i < output.length) { if (output[i].referral_image.length != 0) { output[i].referral_image[0].image_url = _self.imageUrl('t300', output[i].referral_image[0].image_url); } } else { callback(output); } } }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; $scope.dataArrayState = _self.stateData(true, false); _self.getRouteParams(function(params) { var dataSend = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 50, 'txt_sortby': 'faq_index_asc' }; _self.dataSend('referral/lists', dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.resizeImageUrl(output.data.dataList, function(dataList) { $scope.dataArray = dataList; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); }); } } return getFunction; }; $scope.getData().main(); }; return promise; });_ui_share_app.factory('$componentBuy', function componentBuy($routeParams, $timeout) { return });_ui_share_app.directive('componentBuyButtonTypeA', function($rootScope, $routeParams) { var templateName = 'componentBuyButtonTypeA'; var componentMain = 'componentBuy'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', btnstyle: '@btnstyle', id: '@productid', text: '@text', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'icon': '?icon', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; }; return promise; });_ui_share_app.directive('componentBuyButton', function($rootScope, $routeParams, sliderProvider, carouselData, $location) { var templateName = 'componentBuyButton'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', btntwostyle: '@btntwostyle', fonttwostyle: '@fonttwostyle', note: '@note', text: '@text', wait: '@wait', view: '@view', margin: '@margin', id: '@productid', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', animatename: '@animatename', promotelink: '@promotelink', imgcart: '@imgcart', datafont: '@datafont', promotionid: '@promotionid', col: '@col', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = { 'icon': '?icon', 'loading': '?loading', }; promise.controller = function($scope, $timeout, $interval, $q, $window, share) { $scope._col = (typeof $scope.col == 'undefined' || $scope.col == '') ? 15 : parseInt($scope.col); $scope.btntwostyle = (typeof $scope.btntwostyle == 'undefined' || $scope.btntwostyle == '') ? $scope.btnstyle : $scope.btntwostyle; $scope.datacolorfont = (typeof $scope.datafont == 'undefined' || $scope.datafont == '') ? "" : $scope.datafont; // console.log("buyProcess _note :",$scope.note); $scope._note = (typeof $scope.note != 'undefined' && $scope.note != '') ? $scope.note : 0; // console.log("buyProcess _note :",$scope._note); $scope._use_side_promote = (typeof $scope.sidepromote !== 'undefined' && $scope.sidepromote == 'true') ? true : false; $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.promote_link = ''; $scope.promote_text = ''; $scope.temp_added_product = []; $scope.$watch('promotelink', function(newValue, oldValue) { if (!newValue || newValue == "") { return; } var a = newValue.split(","); if (a.length) { $scope.promote_link = encodeURIComponent(a[1]); $scope.promote_text = a[0]; if (CUR_THEME.shop_id() == "459") { $scope.promote_link = "#/"; $scope.promote_link = $scope.promote_link + encodeURIComponent(a[1]); } } }); $scope.currentShopId = parseInt(CUR_THEME.shop_id()); /* check text to allow something */ $scope.useAnimate = function(stringCheck) { var a = $scope.text; var b = a.toLowerCase(); if (b.indexOf(stringCheck) !== -1) { return true; } else { return false; } }; /* default text*/ $scope.textDisplay = { buy: $scope.text || 'Buy Now', wait: $scope.wait || 'Please Wait..', cart: ($scope.useAnimate('buy')) ? 'In Cart' : $scope.view || 'View Cart' }; /* animate : on click */ $scope.animateStartOk = false; $scope.doAnimateStart = function(id, qty) { /* console.log('doAnimateStart: $scope.checkAdded(id)', $scope.checkAdded(id)); console.log('doAnimateStart: $scope.useAnimate(\'buy\')', $scope.useAnimate('buy')); console.log('doAnimateStart: $scope.useAnimate(\'add\')', $scope.useAnimate('add')); console.log('doAnimateStart: $scope.useAnimate(\'shop\')', $scope.useAnimate('shop')); console.log('doAnimateStart: $scope.text', $scope.text); */ console.log("$scope.checkAdded(id) : ", $scope.checkAdded(id)); if ($scope.checkAdded(id)) { if (CUR_THEME.shop_id() == "414") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "723") { $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "741") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "523") { return $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "498") { return $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "528") { return $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "495") { return $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "765") { return $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "738") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "722") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "476") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "401") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "731") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "740") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "355") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "409") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "413") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "474") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "500") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "544") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "598") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "636") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "646") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "676") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "699") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "713") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "717") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "718") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "726") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "728") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "732") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "737") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "740") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "742") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "743") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "745") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "747") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "753") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "754") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "731") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "777") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "783") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "439") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "758") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "459") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "535") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "767") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "770") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "772") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "773") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "774") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "701") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "550") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "762") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "786") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "787") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "776") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "784") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "792") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "795") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "788") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "797") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "785") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else { return UiCart.delegate.modal.open(); } } else { if ($scope.useAnimate('add') || $scope.useAnimate('ตะกร้า') || $scope.useAnimate('order') || $scope.useAnimate('shop') || $scope.useAnimate('buy') || $scope.useAnimate('ซื้อเลย') || $scope.useAnimate('หยิบใส่ตะกร้า') || $scope.useAnimate('เพิ่มในรถเข็น') || $scope.useAnimate('สั่งซื้อเลย') || $scope.useAnimate('สั่งซื้อ') || $scope.useAnimate('หยิบใส่รถเข็น')) { if ($scope.useAnimate('หยิบใส่ตะกร้า')) { $scope.textDisplay.cart = 'ดูตะกร้า'; } else if ($scope.useAnimate('เพิ่มในรถเข็น')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('สั่งซื้อเลย')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('order')) { $scope.textDisplay.cart = 'OPEN CART'; } else if ($scope.useAnimate('สั่งซื้อ')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('เพิ่มในตะกร้า')) { $scope.textDisplay.cart = 'ดูตะกร้า'; } else if ($scope.useAnimate('หยิบใส่รถเข็น')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else { $scope.textDisplay.cart = 'View Cart'; } var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('shown').removeClass('active').removeClass('completedAnimate'); el.addClass('shown'); var a = $timeout(function() { el.addClass('active'); $scope.animateStartOk = true; $timeout.cancel(a); var b = $timeout(function() { $timeout.cancel(b); return $scope.buyProcess(id, qty, false); }, 100); }, 100); } else if ($scope.useAnimate('buy') || $scope.useAnimate('ซื้อ')) { return $scope.buyProcess(id, qty, true); } else { return $scope.buyProcess(id, qty); } } }; /* animate when finish add card */ $scope.failStack = 1; $scope.doAnimateEnd = function(id, qty) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.removeClass('finished'); e.find('.onStart').removeClass('ready').removeClass('next'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; clearClass(id); var el = $('[data-id="animate_of_' + id + '"]'); /* var _a = $interval(function () { if ($scope.checkAdded(id)) { $interval.cancel(_a);*/ var _b = $timeout(function() { $timeout.cancel(_b); el.find('.onStart').addClass('ready'); var _c = $timeout(function() { $timeout.cancel(_c); el.find('.onStart').addClass('next'); el.find('.onFinish').addClass('shown'); var _d = $timeout(function() { el.find('.onFinish').addClass('active'); $timeout.cancel(_d); var _e = $timeout(function() { $timeout.cancel(_e); el.find('.onFinish .txt').addClass('active'); el.addClass('completedAnimate'); $timeout(function() { $scope.doAnimeteFin(id); }, 100); }, 100); }, 100); }, 100); }, 300); /*} else { $scope.failStack++; if ($scope.failStack >= 10) { $interval.cancel(_a); $scope.doAnimateError(id); } } }, 1000);*/ }; /* animate on finish process */ $scope.doAnimeteFin = function(id) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.find('.onStart').removeClass('ready'); e.find('.onStart').removeClass('next'); e.find('.onFinish').removeClass('shown'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; var el = $('[data-id="animate_of_' + id + '"]'); el.addClass('finished'); var aa = $timeout(function() { /* Make Btn Disappear */ el.removeClass('active'); $timeout.cancel(aa); var _aa = $timeout(function() { $timeout.cancel(_aa); /* Remove other class */ el.removeClass('shown'); el.removeClass('completedAnimate'); $timeout.cancel(_aa); el.removeClass('finished'); clearClass(id); $scope.doSideBtnSuccess(id); }, 300); }, 100); }; /* animate on error process */ $scope.doAnimateError = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); alert("เกิดข้อผิดพลาด!\n\n- หากสินค้ามี Option ควรเลือก Option ก่อน \n\n- หากเกิดความไม่สะดวก กรุณาติดต่อเจ้าหน้าที่...\n\nขอบคุณค่ะ"); }; $scope.doAnimateErrorv2 = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); }; /* Side button on success */ $scope.shopState = false; $scope.shopStateShow = false; $scope.doSideBtnSuccess = function(idStr) { var el = $('[data-id="side_of_' + idStr + '"]'); if (CUR_THEME.shop_id() == "530") { $scope.shopStateShow = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "401") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "414") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "500") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "676") { $scope.shopStateShow = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "701") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "726") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "598") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "636") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "465") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "481") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } // if (CUR_THEME.shop_id() == "459") { // $scope.shopState = true; // if (!el.hasClass('active')) { // el.addClass('active'); // var __aa = $timeout(function() { // el.addClass('shown'); // $timeout.cancel(__aa); // }, 100); // } // } if (CUR_THEME.shop_id() == "509") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "535") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "523") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "713") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "718") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "717") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "737") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "699") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "541") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "646") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "728") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "740") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } }; /* check if product on process */ $scope.checkProcess = function() { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; /* check if product added */ $scope.checkAdded = function() { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; $scope.userLogin = function(login, shop_id, callback) { var res_start = false; if (!login && shop_id) { res_start = true; $inloginPopup.open(); } callback(res_start); }; $scope.checkIsLogin = function(callback) { /** **/ var shop_id_array = ["797","800"]; var shop_id_this = CUR_THEME.shop_id(); /** **/ var is_login = UiCustomerBox.delegate.get.isLogin(); var shop_id_start = shop_id_array.includes(shop_id_this); $scope.userLogin(is_login, shop_id_start, function(res_start) { callback(res_start); }); }; /* user click add/buy button */ $scope.onPress = function() { $scope.checkIsLogin(function(res_start) { if (!res_start) { var checkToDetail = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; console.log("onPress checkToDetail : ", checkToDetail); if (checkToDetail) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + $scope.id; } return window.location.href = "#/product-detail/" + $scope.id; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); /*if(!isMobile){ $scope.doAnimateStart($scope.id, _qty); } else { $scope.buyProcess($scope.id, _qty, true); } */ } } }); }; /* buy function * @params {product_id} product id (parent product or option product) * @params {quantity} quantity to add * @params {byPassAnimate} bypass animate to skip to cart view */ $scope.buyProcess = function(product_id, quantity, byPassAnimate) { // console.log("buyProcess 1", product_id, quantity); var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { // console.log("buyProcess 2", product_id, quantity); console.log("buyProcess : adding cahecked", $scope.id, quantity, $scope.promotionid); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid, function(e) { console.log("buyProcess: callback", e); if (e !== false) { if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } /* check store.js */ if (typeof store !== 'undefined' && store != undefined) { store.set('gae_cart_id', e.cart_id); /* doc: https://github.com/marcuswestin/store.js */ } if ($scope.currentShopId == 500) { if ($('.modalpopup').hasClass('open')) { $('.modalpopup').removeClass('open'); } } // console.log("buyProcess 2.5", product_id, quantity); // console.log("buyProcess _note :",$scope._note); if ($scope._note != 0) { $("#intro" + product_id).addClass("active"); } /* Virtual Cart Refresh */ if ($scope.currentShopId == 762) {} else { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return $scope.doAnimateEnd(product_id, quantity); } else { switch ($scope.currentShopId) { case 701: return window.location.href = "product-detail/" + $scope.id; case 717: return $scope.doAnimateErrorv2(product_id); default: return $scope.doAnimateError(product_id); break; } } }); } else { // console.log("buyProcess 3", product_id, quantity); if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } $scope.doAnimateEnd(product_id, quantity); return UiCart.delegate.modal.open(); } } /*eturn UiCart.delegate.modal.open();*/ }; $scope.virtualCartRefresh = function() { var shop_id = $scope.currentShopId; switch (shop_id) { /* virtualCart */ case 414: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 699: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCart() */ break; case 741: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 401: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 523: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 723: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 528: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 498: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; default: $scope.virtualCart('fetch', 'fetch'); /* virtualCart() */ break; /* virtualCart */ /* virtualCartTypeA */ case 409: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 413: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 500: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 635: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 737: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; /* virtualCartTypeA */ /* virtualCartTypeB */ case 738: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 355: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 459: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 474: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 495: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 544: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 598: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 636: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 646: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 676: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 699: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 713: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 717: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 718: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 726: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 728: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 740: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 732: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 742: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 743: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 745: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 747: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 753: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 754: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 758: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 701: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 772: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 550: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 731: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 777: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 783: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 786: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 787: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 792: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; /* virtualCartTypeB */ /* urlViewcart */ case 765: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 762: $scope.windowLocationUrl('viewcart'); /* windowLocationUrl() */ break; /* urlViewcart */ case 788: $scope.trumpComponentCarts(); /* trumpComponentCarts() */ break; case 785: $scope.trumpComponentCarts(); /* trumpComponentCarts() */ break; case 795: $scope.trumpComponentCarts(); /* trumpComponentCarts() */ break; case 797: $scope.trumpComponentCarts(); /* trumpComponentCarts() */ break; } }; $scope.trumpComponentCarts = function() { var controlCart = share.getTrumpComponentCarts(); var component_carts = $('.cover-cards').hasClass('active'); if (!component_carts) { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.cart(); } } else { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.load(); } } }; $scope.virtualCart = function(functionone, functiontwo) { var root_virtual_cart = $('#root-virtual-cart').hasClass('is-open'); if (!root_virtual_cart) { /* open virtual cart & refresh virtual cart */ if (functionone == 'open') { return $virtualCart.open(); } else if (functionone == 'fetch') { return $virtualCart.fetch(); } } else { /* refresh virtual cart */ if (functiontwo == 'open') { return $virtualCart.open(); } else if (functiontwo == 'fetch') { return $virtualCart.fetch(); } } }; $scope.virtualCartTypeA = function(functionone, functiontwo) { var root_virtual_cart_type_a = $('#root-virtual-cart-type-a').hasClass('is-open'); if (!root_virtual_cart_type_a) { if (functionone == 'isOpenOrClose') { return $virtualCartTypeA.isOpenOrClose(); } else if (functionone == 'load') { return $virtualCartTypeA.load(); } } else { if (functiontwo == 'isOpenOrClose') { return $virtualCartTypeA.isOpenOrClose(); } else if (functiontwo == 'load') { return $virtualCartTypeA.load(); } } }; $scope.virtualCartTypeB = function(functionone, functiontwo) { var root_virtual_cart_type_b = $('#root-virtual-cart-type-b').hasClass('show'); if (!root_virtual_cart_type_b) { if (functionone == 'isCart') { return $virtualCartTypeB.isCart(); } else if (functionone == 'isLoad') { return $virtualCartTypeB.isLoad(); } } else { if (functiontwo == 'isCart') { return $virtualCartTypeB.isCart(); } else if (functiontwo == 'isLoad') { return $virtualCartTypeB.isLoad(); } } }; $scope.windowLocationUrl = function(page_in) { $location.url(page_in).replace(); }; $scope.saveProductNote = function(id) { var product_id = id; var product_qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; if (product_qty <= 0) { product_qty = 1; } var product_note = $('#introdetail' + id).val(); if (product_note == "") { // console.log("buyProcess : saveProductNote : 1", product_note); $scope.popupClose(product_id); } else { UiCart.delegate.product.updateAmountNote(product_id, product_qty, product_note, function(e) { // console.log("buyProcess : saveProductNote : 2", e); $scope.popupClose(product_id); }); } /* Virtual Cart Refresh */ $scope.virtualCartRefresh(); /* virtualCartRefresh */ }; $scope.popupClose = function(product_id) { $("#intro" + product_id).removeClass("active"); $('.round').val('').blur(); }; $scope.checkAddedClass = function() { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; /* Check if animate start */ $scope.animateStartOk = function() {}; /* Calculate Width Of Btn */ $scope.calWidth = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerWidth(true); }; /* Calculate Height Of Btn */ $scope.calHeight = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); }; /* Calculate margin calMarginTop Of Btn */ $scope.calMarginTop = function() { var a = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); var b = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(true); var c = a + ((b - a) / 2); return '-' + c + 'px'; }; /* Calculate margin left Of Btn */ $scope.calMarginLeft = function() { if (typeof $('[data-id="buy_of_' + $scope.id + '"]').position() !== 'undefined') { var l = $('[data-id="buy_of_' + $scope.id + '"]').position().left; return (l - $scope._col) + 'px'; } return '0px'; }; }; return promise; });_ui_share_app.directive('componentBuyButtonAa', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonAa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', btntwostyle: '@btntwostyle', fonttwostyle: '@fonttwostyle', text: '@text', wait: '@wait', view: '@view', margin: '@margin', id: '@productid', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', animatename: '@animatename', promotelink: '@promotelink', imgcart: '@imgcart', promotionid: '@promotionid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = { 'icon': '?icon', 'loading': '?loading', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.btntwostyle = (typeof $scope.btntwostyle == 'undefined' || $scope.btntwostyle == '') ? $scope.btnstyle : $scope.btntwostyle; $scope._use_side_promote = (typeof $scope.sidepromote !== 'undefined' && $scope.sidepromote == 'true') ? true : false; $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.promote_link = ''; $scope.promote_text = ''; $scope.temp_added_product = []; $scope.$watch('promotelink', function(newValue, oldValue) { if (!newValue || newValue == "") { return; } var a = newValue.split(","); if (a.length) { $scope.promote_link = encodeURIComponent(a[1]); $scope.promote_text = a[0]; if (CUR_THEME.shop_id() == "459") { $scope.promote_link = "#/"; $scope.promote_link = $scope.promote_link + encodeURIComponent(a[1]); } } }); $scope.currentShopId = parseInt(CUR_THEME.shop_id()); /* check text to allow something */ $scope.useAnimate = function(stringCheck) { var a = $scope.text; var b = a.toLowerCase(); if (b.indexOf(stringCheck) !== -1) { return true; } else { return false; } }; /* default text*/ $scope.textDisplay = { buy: $scope.text || 'Buy Now', wait: $scope.wait || 'Please Wait..', cart: ($scope.useAnimate('buy')) ? 'In Cart' : $scope.view || 'View Cart' }; /* animate : on click */ $scope.animateStartOk = false; $scope.doAnimateStart = function(id, qty) { /*console.log('doAnimateStart: $scope.checkAdded(id)', $scope.checkAdded(id)); console.log('doAnimateStart: $scope.useAnimate(\'buy\')', $scope.useAnimate('buy')); console.log('doAnimateStart: $scope.useAnimate(\'add\')', $scope.useAnimate('add')); console.log('doAnimateStart: $scope.useAnimate(\'shop\')', $scope.useAnimate('shop')); console.log('doAnimateStart: $scope.text', $scope.text);*/ if ($scope.checkAdded(id)) { if (CUR_THEME.shop_id() == "414") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "699") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "717") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "718") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "676") { // var pathString = 'viewcart'; return window.location.href = 'viewcart'; } else { return UiCart.delegate.modal.open(); } } if ($scope.useAnimate('add') || $scope.useAnimate('ตะกร้า') || $scope.useAnimate('order') || $scope.useAnimate('shop') || $scope.useAnimate('buy') || $scope.useAnimate('ซื้อเลย') || $scope.useAnimate('สั่งซื้อ') || $scope.useAnimate('เพิ่มในรถเข็น') || $scope.useAnimate('สั่งซื้อเลย')) { if ($scope.useAnimate('สั่งซื้อ')) { $scope.textDisplay.cart = 'ดูตะกร้า'; } else if ($scope.useAnimate('เพิ่มในรถเข็น')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('สั่งซื้อเลย')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('order')) { $scope.textDisplay.cart = 'OPEN CART'; } else { $scope.textDisplay.cart = 'View Cart'; } var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('shown').removeClass('active').removeClass('completedAnimate'); el.addClass('shown'); var a = $timeout(function() { el.addClass('active'); $scope.animateStartOk = true; $timeout.cancel(a); var b = $timeout(function() { $timeout.cancel(b); return $scope.buyProcess(id, qty, false); }, 100); }, 100); } else if ($scope.useAnimate('buy') || $scope.useAnimate('ซื้อ')) { return $scope.buyProcess(id, qty, true); } else { return $scope.buyProcess(id, qty); } }; /* animate when finish add card */ $scope.failStack = 1; $scope.doAnimateEnd = function(id, qty) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.removeClass('finished'); e.find('.onStart').removeClass('ready').removeClass('next'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; clearClass(id); var el = $('[data-id="animate_of_' + id + '"]'); /* var _a = $interval(function () { if ($scope.checkAdded(id)) { $interval.cancel(_a);*/ var _b = $timeout(function() { $timeout.cancel(_b); el.find('.onStart').addClass('ready'); var _c = $timeout(function() { $timeout.cancel(_c); el.find('.onStart').addClass('next'); el.find('.onFinish').addClass('shown'); var _d = $timeout(function() { el.find('.onFinish').addClass('active'); $timeout.cancel(_d); var _e = $timeout(function() { $timeout.cancel(_e); el.find('.onFinish .txt').addClass('active'); el.addClass('completedAnimate'); $timeout(function() { $scope.doAnimeteFin(id); }, 100); }, 100); }, 100); }, 100); }, 300); /*} else { $scope.failStack++; if ($scope.failStack >= 10) { $interval.cancel(_a); $scope.doAnimateError(id); } } }, 1000);*/ }; /* animate on finish process */ $scope.doAnimeteFin = function(id) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.find('.onStart').removeClass('ready'); e.find('.onStart').removeClass('next'); e.find('.onFinish').removeClass('shown'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; var el = $('[data-id="animate_of_' + id + '"]'); el.addClass('finished'); var aa = $timeout(function() { /* Make Btn Disappear */ el.removeClass('active'); $timeout.cancel(aa); var _aa = $timeout(function() { $timeout.cancel(_aa); /* Remove other class */ el.removeClass('shown'); el.removeClass('completedAnimate'); $timeout.cancel(_aa); el.removeClass('finished'); clearClass(id); $scope.doSideBtnSuccess(id); }, 300); }, 100); }; /* animate on error process */ $scope.doAnimateError = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); /*alert("เกิดข้อผิดพลาด!\n\n- หากสินค้ามี Option ควรเลือก Option ก่อน \n\n- หากเกิดความไม่สะดวก กรุณาติดต่อเจ้าหน้าที่...\n\nขอบคุณค่ะ");*/ }; /* Side button on success */ $scope.shopState = false; $scope.shopStateShow = false; $scope.doSideBtnSuccess = function(idStr) { var el = $('[data-id="side_of_' + idStr + '"]'); if (CUR_THEME.shop_id() == "530") { $scope.shopStateShow = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "401") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "414") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "500") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "676") { $scope.shopStateShow = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "701") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "598") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "636") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "465") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "481") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "459") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "509") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "535") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "523") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "713") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "718") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "699") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "717") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "541") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "646") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } }; /* check if product on process */ $scope.checkProcess = function() { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; /* check if product added */ $scope.checkAdded = function() { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; /* user click add/buy button */ $scope.onPress = function() { var checkToDetail = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; if (checkToDetail) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + $scope.id; } return window.location.href = "#/product-detail/" + $scope.id; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); /*if(!isMobile){ $scope.doAnimateStart($scope.id, _qty); } else { $scope.buyProcess($scope.id, _qty, true); } */ } }; /* buy function * @params {product_id} product id (parent product or option product) * @params {quantity} quantity to add * @params {byPassAnimate} bypass animate to skip to cart view */ $scope.buyProcess = function(product_id, quantity, byPassAnimate) { console.log("buyProcess 1", product_id, quantity); var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { console.log("buyProcess 2", product_id, quantity); console.log("buyProcess : adding", $scope.id, quantity); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid, function(e) { console.log("buyProcess: callback", e); if (e !== false) { if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } /* check store.js */ if (typeof store !== 'undefined' && store != undefined) { store.set('gae_cart_id', e.cart_id); /* doc: https://github.com/marcuswestin/store.js */ } console.log("buyProcess 2.5", product_id, quantity); /* Virtual Cart Refresh */ if ($('.virtual-view-container').length > 0) { if (!$('#root-virtual-cart').hasClass('is-open')) { switch ($scope.currentShopId) { case 500: /* missmonribs */ /* open virtual cart & refresh virtual cart */ $virtualCart.open(); break; case 414: /* open virtual cart & refresh virtual cart */ $virtualCart.open(); break; default: /* refresh virtual cart */ $virtualCart.fetch(); break; } } else { /* refresh virtual cart */ $virtualCart.fetch(); } } /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return $scope.doAnimateEnd(product_id, quantity); } else { switch ($scope.currentShopId) { case 701: return window.location.href = "product-detail/" + $scope.id; break; case 717: return $scope.doAnimateError(product_id); break; default: return $scope.doAnimateError(product_id); break; } } }); } else { console.log("buyProcess 3", product_id, quantity); if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } $scope.doAnimateEnd(product_id, quantity); return UiCart.delegate.modal.open(); } } /*eturn UiCart.delegate.modal.open();*/ }; $scope.checkAddedClass = function() { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; /* Check if animate start */ $scope.animateStartOk = function() {}; /* Calculate Width Of Btn */ $scope.calWidth = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerWidth(true); }; /* Calculate Height Of Btn */ $scope.calHeight = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); }; /* Calculate margin calMarginTop Of Btn */ $scope.calMarginTop = function() { var a = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); var b = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(true); var c = a + ((b - a) / 2); return '-' + c + 'px'; }; /* Calculate margin left Of Btn */ $scope.calMarginLeft = function() { if (typeof $('[data-id="buy_of_' + $scope.id + '"]').position() !== 'undefined') { var l = $('[data-id="buy_of_' + $scope.id + '"]').position().left; return (l - 15) + 'px'; } return '0px'; }; }; return promise; }); window.$componentBuyButtonAttribute = window.$componentBuyButtonAttribute || { /* constructor*/ __constructor: function(){ console.log("this is constructor => Init"); console.log("this is constructor => Init"); console.log("this is constructor => Init"); }, /* Init / Config */ templatePath: _ui_share_host + 'componentBuyButtonAttribute/', checkRoot: function () { var test = document.querySelector('body #root-buy-button-attribute'); return (test == null || test == undefined) ? false : true; }, initRoot: function () { if (!this.checkRoot()) { var el = document.createElement('div'); el.setAttribute('id', 'root-buy-button-attribute'); document.querySelector('body').appendChild(el); this.importHTMLCore(); this.importCSSCore(); } }, importCSSCore: function () { var c = document.createElement('style'); c.type = 'text/css'; c.id = 'root-buy-button-attribute-style'; c.setAttribute('rel', 'stylesheet'); c.setAttribute('href', this.templatePath + 'componentBuyButtonAttribute.css'); document.querySelector('head').appendChild(c); }, importHTMLCore: function () { var r = $.ajax({ url: this.templatePath + 'componentBuyButtonAttribute.html', method: "GET", data: { id: 1 }, dataType: "html" }); r.done(function (receiveData) { document.querySelector('body #root-buy-button-attribute').innerHTML = receiveData; }); r.fail(function (jqXHR, textStatus) { document.querySelector('body #root-buy-button-attribute').innerHTML = ''; }); }, title: function (str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }, /* Native func */ hasClass: function (el, className) { if (el.classList){ return el.classList.contains(className); } else { return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)')); } }, addClass: function (el, className) { if (el.classList) { el.classList.add(className) } else if (!hasClass(el, className)){ el.className += " " + className; }; }, removeClass: function (el, className) { if (el.classList){ el.classList.remove(className) } else if (hasClass(el, className)) { var reg = new RegExp('(\\s|^)' + className + '(\\s|$)'); el.className = el.className.replace(reg, ' '); } }, /* Action */ active: function (productId) { if (!this.hasClass(document.querySelector('#root-buy-button-attribute .container_buy_attribute'), 'active')) { this.addClass(document.querySelector('#root-buy-button-attribute .container_buy_attribute'), 'active'); document.querySelector('body').style.position = 'fixed'; document.querySelector('body').style.overflow = 'hidden'; document.querySelector('body').style.width = '100%'; this.getProduct(productId); } }, unActive: function () { if (this.hasClass(document.querySelector('#root-buy-button-attribute .container_buy_attribute'), 'active')) { this.removeClass(document.querySelector('#root-buy-button-attribute .container_buy_attribute'), 'active'); document.querySelector('body').style.position = ''; document.querySelector('body').style.overflow = ''; document.querySelector('body').style.width = ''; document.querySelector('#root-buy-button-attribute .container_buy_attribute .content_2').innerHTML = ''; document.querySelector('#root-buy-button-attribute .container_buy_attribute .content_2').style.display = 'none'; document.querySelector('#root-buy-button-attribute .container_buy_attribute .content_1').style.display = 'block'; } }, reActive: function () { this.unActive(); this.active(); }, productOptionLevelArray: [], optionToCalculateNext: false, optionNotFound: 0, productData: false, selectedOptionTextJson: '', chageProductByOptionId: function(masterIndex, childIndex, optionId) { function compareArray(array_a, array) { if (!array){ return false; } if (array_a.length != array.length){ return false; } for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var self = this; /* class active */ $('#root-buy-button-attribute').find('.list_option[data-master="'+masterIndex+'"]').removeClass('active'); $('#root-buy-button-attribute').find('.list_option[data-master="'+masterIndex+'"][data-child="'+childIndex+'"]').addClass('active'); this.productOptionLevelArray[masterIndex].level_data = optionId; /*console.log('$scope.productOptionLevelArray: clicked!', self.productOptionLevelArray);*/ var optionSelectedArray = []; for (var i = 0; i < this.productOptionLevelArray.length; i++) { if (this.productOptionLevelArray[i].level_data != 0) { optionSelectedArray.push(this.productOptionLevelArray[i].level_data); } } if (optionSelectedArray.length == this.productData.product_attribute.option_data.pclass_array.length) { this.optionToCalculateNext = true; } if (!this.optionToCalculateNext) { return; } this.optionNotFound = 0; for (var i = 0; i < this.productData.product_attribute.option_data.variant_array.length; i++) { var _self = this.productData.product_attribute.option_data.variant_array[i]; var _self_option = JSON.parse(_self.option_id_json); if (compareArray(optionSelectedArray, _self_option)) { this.productData.product_id = _self.product_id; this.productData.product_price = _self.price; this.productData.product_sku = _self.sku; this.productData.product_variant_compare_price = _self.compare_price; this.selectedOptionTextJson = _self.option_id_json; /* Find Image Variant */ this.optionNotFound = 0; $('#root-buy-button-attribute').find('.item_3 .section_2 #product-price .n').text(this.productData.product_price); $('#root-buy-button-attribute').find('.item_3 .section_2 #product-price').show(); $('#root-buy-button-attribute').find('.item_3 .section_2 #product-buy').show(); $('#root-buy-button-attribute').find('#product-buy').attr('data-id',this.productData.product_id); $('#root-buy-button-attribute').find('#product-buy').attr('data-qty',1); break; } else { this.optionNotFound++; $('#root-buy-button-attribute').find('.item_3 .section_2 #product-price').hide(); $('#root-buy-button-attribute').find('.item_3 .section_2 #product-buy').hide(); $('#root-buy-button-attribute').find('#product-buy').attr('data-id', '').attr('data-qty', '').css('background-color','#609e5c').text('Add To Cart'); } } }, buyProduct: function(){ var product_id = $('#root-buy-button-attribute').find('#product-buy').attr('data-id'); var quantity = $('#root-buy-button-attribute').find('#product-buy').attr('data-qty'); if(product_id !== '' && quantity !== ''){ $('#root-buy-button-attribute').find('#product-buy').css('background-color','#b3b3b3').text('Please wait..'); if (!UiCart.delegate.product.isSelected(product_id) && !UiCart.delegate.product.isProgress(product_id)) { UiCart.delegate.product.add(product_id, quantity,0, function(e){ if(e !== false){ setTimeout(function(){ $('#root-buy-button-attribute').find('#product-buy').css('background-color','#609e5c').text('Done'); },500); } }); } } }, /* Render */ getProduct: function (id) { var self = this; this.productOptionLevelArray= []; this.optionToCalculateNext= false; this.optionNotFound= 0; this.productData= false; this.selectedOptionTextJson= ''; var r = $.ajax({ url: 'https://missmonribs.getappeasy.com/store/api/v1/product/id?txt_product_id=' + id, method: "GET", dataType: "json" }); r.done(function (receiveData) { if (receiveData.ok == 1) { self.productData = receiveData.data; self.renderItem(receiveData.data); } else { self.unActive(); window.location.href = "product-detail/" + id; } }); }, renderThumbnail: function(size, objectArray){ if(!objectArray.length){ return "-"; } var self = this; return self.viewOptimizeImage(size, objectArray[0].image_url,objectArray[0].image_width); }, renderItem: function (objectData) { var self = this; var r = $.ajax({ url: this.templatePath + 'item.php', method: "POST", data: { item: objectData, title: self.title(objectData.product_title), thumbnail: self.renderThumbnail(100, objectData.product_image) }, dataType: "html" }); r.done(function (e) { document.querySelector('#root-buy-button-attribute .container_buy_attribute .content_1').style.display = 'none'; document.querySelector('#root-buy-button-attribute .container_buy_attribute .content_2').style.display = 'block'; document.querySelector('#root-buy-button-attribute .container_buy_attribute .content_2').innerHTML = e; self.renderVariant(objectData); }); }, renderVariant: function (objectData) { if (typeof objectData.product_attribute.option_data !== 'undefined' && objectData.product_total_variant > 0) { if (typeof objectData.product_attribute.option_data.pclass_array !== 'undefined' && objectData.product_attribute.option_data.pclass_array.length) { /*$scope.buildMultipleQuantity(e.data);*/ for (var op = 0; op < objectData.product_attribute.option_data.pclass_array.length; op++) { this.productOptionLevelArray.push({ level_index: op, level_id: objectData.product_attribute.option_data.pclass_array[op].pclass_id, level_label: objectData.product_attribute.option_data.pclass_array[op].pclass_name, level_data: 0 }); } if (!objectData.product_attribute.option_data.variant_array.length) { this.optionToCalculateNext = true; } } else { this.optionToCalculateNext = true; } } else { this.optionToCalculateNext = true; } console.log("renderVariant: productOptionLevelArray", this.productOptionLevelArray); var self = this; var r = $.ajax({ url: this.templatePath + 'variant.php', method: "POST", data: { item: objectData }, dataType: "html" }); r.done(function (e) { document.querySelector('#root-buy-button-attribute .container_buy_attribute .content_2 .item_2 .wait_2').style.display = 'none'; document.querySelector('#root-buy-button-attribute .container_buy_attribute .content_2 .item_2').innerHTML = e; }); }, /* Optimize image size by device pixel * @params {size} (integer) prefer size * @params {image_url} (string) original image source link * @params {image_width} (string) original image width * @return string */ viewOptimizeImage:function(size, image_url, image_width){ if(window.devicePixelRatio >= 2 || parseInt(image_width) <= size){ return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't'+size+'_' + b; return a.join("/"); }, }; $(function () { switch(parseInt(CUR_THEME.shop_id())){ case 500: /* missmonribs */ $componentBuyButtonAttribute.initRoot(); break; } }); _ui_share_app.directive('componentBuyButtonB', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', text: '@text', margin: '@margin', id: '@productid', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', promotionid: '@promotionid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.checkProcess = function() { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; $scope.checkAdded = function() { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; $scope.onPress = function() { var d = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; if (d) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + productId; } return window.location.href = "#/product-detail/" + productId; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; $scope.buyProcess($scope.id, _qty); } }; $scope.buyProcess = function(product_id, quantity) { var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { console.log("adding", $scope.id, quantity); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid); /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return; } else { return UiCart.delegate.modal.open(); } } return UiCart.delegate.modal.open(); }; $scope.checkAddedClass = function() { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; }; return promise; }); _ui_share_app.directive('componentBuyButtonC', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle:'@btnstyle', text:'@text', margin:'@margin', id:'@productid', qty:'@qty', godetail:'@godetail', requirelogin:'@requirelogin', datahover:'@datahover', promotionid: '@promotionid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.checkProcess = function(){ return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; $scope.checkAdded = function(){ return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; $scope.onPress = function(){ var d = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; if(d){ if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + productId; } return window.location.href = "#/product-detail/" + productId; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; $scope.buyProcess($scope.id, _qty); } }; $scope.buyProcess = function(product_id, quantity){ var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { console.log("adding", $scope.id, quantity); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid); /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return; } else { return UiCart.delegate.modal.open(); } } return UiCart.delegate.modal.open(); }; $scope.checkAddedClass = function(){ var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function(){ if(CUR_THEME.shop_id()==536){ return true; } return false; }; }; return promise; });_ui_share_app.directive('componentBuyButtonD', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', text: '@text', margin: '@margin', id: '@productid', price: '@price', total: '@total', note: '@note', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', animatename: '@animatename', promotelink: '@promotelink', productdetail: '@productdetail', promotionid: '@promotionid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._use_side_promote = (typeof $scope.sidepromote !== 'undefined' && $scope.sidepromote == 'true') ? true : false; $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.promote_link = ''; $scope.promote_text = ''; $scope.temp_added_product = []; $scope.$watch('promotelink', function(newValue, oldValue) { if (!newValue || newValue == "") { return; } var a = newValue.split(","); if (a.length) { $scope.promote_link = encodeURIComponent(a[1]); $scope.promote_text = a[0]; } }); /* check text to allow something */ $scope.useAnimate = function(stringCheck) { var a = $scope.text; var b = a.toLowerCase(); if (b.indexOf(stringCheck) !== -1) { return true; } else { return false; } }; /* default text*/ $scope.textDisplay = { buy: $scope.text || 'Buy Now', wait: 'Please Wait..', cart: ($scope.useAnimate('buy')) ? 'In Cart' : 'ดูตะกร้าสินค้า' }; /* animate : on click */ $scope.animateStartOk = false; $scope.doAnimateStart = function(id, qty) { /*console.log('doAnimateStart: $scope.checkAdded(id)', $scope.checkAdded(id)); console.log('doAnimateStart: $scope.useAnimate(\'buy\')', $scope.useAnimate('buy')); console.log('doAnimateStart: $scope.useAnimate(\'add\')', $scope.useAnimate('add')); console.log('doAnimateStart: $scope.useAnimate(\'shop\')', $scope.useAnimate('shop')); console.log('doAnimateStart: $scope.text', $scope.text);*/ if ($scope.checkAdded(id)) { /* return UiCart.delegate.modal.open();*/ return $virtualCart.open(); } if ($scope.useAnimate('add') || $scope.useAnimate('ตะกร้า') || $scope.useAnimate('order')) { $scope.textDisplay.cart = 'ดูตะกร้าสินค้า'; var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('shown').removeClass('active').removeClass('completedAnimate'); el.addClass('shown'); var a = $timeout(function() { el.addClass('active'); $scope.animateStartOk = true; $timeout.cancel(a); var b = $timeout(function() { $timeout.cancel(b); return $scope.buyProcess(id, qty, false); }, 100); }, 100); } else if ($scope.useAnimate('buy') || $scope.useAnimate('ซื้อ')) { return $scope.buyProcess(id, qty, true); } else { return $scope.buyProcess(id, qty); } }; /* animate when finish add card */ $scope.failStack = 1; $scope.doAnimateEnd = function(id, qty) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.removeClass('finished'); e.find('.onStart').removeClass('ready').removeClass('next'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; clearClass(id); var el = $('[data-id="animate_of_' + id + '"]'); /* var _a = $interval(function () { if ($scope.checkAdded(id)) { $interval.cancel(_a);*/ var _b = $timeout(function() { $timeout.cancel(_b); el.find('.onStart').addClass('ready'); var _c = $timeout(function() { $timeout.cancel(_c); el.find('.onStart').addClass('next'); el.find('.onFinish').addClass('shown'); var _d = $timeout(function() { el.find('.onFinish').addClass('active'); $timeout.cancel(_d); var _e = $timeout(function() { $timeout.cancel(_e); el.find('.onFinish .txt').addClass('active'); el.addClass('completedAnimate'); $timeout(function() { $scope.doAnimeteFin(id); }, 100); }, 100); }, 100); }, 100); }, 300); /*} else { $scope.failStack++; if ($scope.failStack >= 10) { $interval.cancel(_a); $scope.doAnimateError(id); } } }, 1000);*/ }; /* animate on finish process */ $scope.doAnimeteFin = function(id) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.find('.onStart').removeClass('ready'); e.find('.onStart').removeClass('next'); e.find('.onFinish').removeClass('shown'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; var el = $('[data-id="animate_of_' + id + '"]'); el.addClass('finished'); var aa = $timeout(function() { /* Make Btn Disappear */ el.removeClass('active'); $timeout.cancel(aa); var _aa = $timeout(function() { $timeout.cancel(_aa); /* Remove other class */ el.removeClass('shown'); el.removeClass('completedAnimate'); $timeout.cancel(_aa); el.removeClass('finished'); clearClass(id); $scope.doSideBtnSuccess(id); }, 300); }, 100); }; /* animate on error process */ $scope.doAnimateError = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); /* alert("เกิดข้อผิดพลาด!\n\n- หากสินค้ามี Option ควรเลือก Option ก่อน \n\n- หากเกิดความไม่สะดวก กรุณาติดต่อเจ้าหน้าที่...\n\nขอบคุณค่ะ");*/ }; /* Side button on success */ $scope.doSideBtnSuccess = function(idStr) { var el = $('[data-id="side_of_' + idStr + '"]'); if (CUR_THEME.shop_id() == "500") { if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "701") { if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "598") { if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "636") { if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } }; /* check if product on process */ $scope.checkProcess = function() { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; /* check if product added */ $scope.checkAdded = function() { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; /* user click add/buy button */ $scope.onPress = function() { if ($scope.price != 0 && $scope.total != 0) { var checkToDetail = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; if (checkToDetail) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + $scope.id; } return window.location.href = "#/product-detail/" + $scope.id; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); /*if(!isMobile){ $scope.doAnimateStart($scope.id, _qty); } else { $scope.buyProcess($scope.id, _qty, true); } */ } } }; /* buy function * @params {product_id} product id (parent product or option product) * @params {quantity} quantity to add * @params {byPassAnimate} bypass animate to skip to cart view */ $scope.buyProcess = function(product_id, quantity, byPassAnimate) { console.log("buyProcess 1", product_id, quantity); var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { console.log("buyProcess 2", product_id, quantity); console.log("buyProcess : adding", $scope.id, quantity); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid, function(e) { console.log("buyProcess: callback", e); if (e !== false) { if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } console.log("buyProcess 2.5", product_id, quantity); /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); /* Show popup */ /* $("#intro" + product_id).addClass("active"); */ if ($scope.note != 0) { $("#intro" + product_id).addClass("active"); } if ($('.virtual-view-container').length > 0) { if (!$('#root-virtual-cart').hasClass('is-open')) { $virtualCart.open(); } else { $virtualCart.fetch(); } } /* animate stop */ return $scope.doAnimateEnd(product_id, quantity); } else { if ($scope.viewRouteParams().referral_type == undefined) { return $scope.doAnimateError(product_id); } else { /*return window.location.href = "product-detail/" + product_id + "?referral_name=" + $scope.viewRouteParams().referral_name;*/ return window.location.href = $scope.productdetail; } } }); } else { console.log("buyProcess 3", product_id, quantity); if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } $scope.doAnimateEnd(product_id, quantity); return UiCart.delegate.modal.open(); } } /*eturn UiCart.delegate.modal.open();*/ }; $scope.saveProductNote = function(id) { var product_id = id; var product_qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; if (product_qty <= 0) { product_qty = 1; } var product_note = $('#introdetail' + id).val(); $virtualCart.fetch(); /*if ($('.virtual-view-container').length > 0) { if (!$('#root-virtual-cart').hasClass('is-open')) { $virtualCart.open(); } else { $virtualCart.fetch(); } }*/ if (product_note == "") { console.log("buyProcess : saveProductNote : 1", product_note); return $scope.popupClose(product_id); } else { UiCart.delegate.product.updateAmountNote(product_id, product_qty, product_note, function(e) { console.log("buyProcess : saveProductNote : 2", e); return $scope.popupClose(product_id); }); } }; $scope.popupClose = function(product_id) { $("#intro" + product_id).removeClass("active"); $('.round').val('').blur(); /* $scope.show_branch = $("#data-dropdown option:selected").text();*/ }; $scope.checkAddedClass = function() { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; /* Check if animate start */ $scope.animateStartOk = function() {}; /* Calculate Width Of Btn */ $scope.calWidth = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerWidth(true); }; /* Calculate Height Of Btn */ $scope.calHeight = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerHeight() + 1; }; /* Calculate margin calMarginTop Of Btn */ $scope.calMarginTop = function() { var a = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); var b = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(true); var c = (a + ((b - a) / 2)); return '-' + (c + 10) + 'px'; }; /* Calculate margin left Of Btn */ $scope.calMarginLeft = function() { if (typeof $('[data-id="buy_of_' + $scope.id + '"]').position() !== 'undefined') { var l = $('[data-id="buy_of_' + $scope.id + '"]').position().left; return (l - 15) + 'px'; } return '0px'; }; $scope.viewRouteParams = function() { return $routeParams || false; }; }; return promise; });_ui_share_app.directive('componentBuyButtonE', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', iconname: '@iconname', text: '@text', margin: '@margin', id: '@productid', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', animatename: '@animatename', promotelink: '@promotelink', view: '@view', fontcolor: '@fontcolor', promotionid: '@promotionid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $location) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.iconname = (typeof $scope.iconname !== '') ? 'icnt_fill_cart02_light' : false; $scope._use_side_promote = (typeof $scope.sidepromote !== 'undefined' && $scope.sidepromote == 'true') ? true : false; $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.promote_link = ''; $scope.promote_text = ''; $scope.currentShopId = parseInt(CUR_THEME.shop_id()); $scope.temp_added_product = []; $scope.$watch('promotelink', function(newValue, oldValue) { if (!newValue || newValue == "") { return; } var a = newValue.split(","); if (a.length) { $scope.promote_link = encodeURIComponent(a[1]); $scope.promote_text = a[0]; } }); /* check text to allow something */ $scope.useAnimate = function(stringCheck) { var a = $scope.text; var b = a.toLowerCase(); if (b.indexOf(stringCheck) !== -1) { return true; } else { return false; } }; /* default text*/ $scope.textDisplay = { buy: $scope.text || 'Buy Now', wait: 'Please Wait..', cart: ($scope.useAnimate('buy')) ? 'In Cart' : $scope.view || 'View Cart' }; // cart: ($scope.useAnimate('buy')) ? 'In Cart' : 'View Cart' /* animate : on click */ $scope.animateStartOk = false; $scope.doAnimateStart = function(id, qty) { /*console.log('doAnimateStart: $scope.checkAdded(id)', $scope.checkAdded(id)); console.log('doAnimateStart: $scope.useAnimate(\'buy\')', $scope.useAnimate('buy')); console.log('doAnimateStart: $scope.useAnimate(\'add\')', $scope.useAnimate('add')); console.log('doAnimateStart: $scope.useAnimate(\'shop\')', $scope.useAnimate('shop')); console.log('doAnimateStart: $scope.text', $scope.text);*/ if ($scope.checkAdded(id)) { if (CUR_THEME.shop_id() == "635") { // return window.location.href = 'viewcart'; // var pathString = 'viewcart'; // return $location.path(pathString); $scope.virtualCartRefreshIn(); } else if (CUR_THEME.shop_id() == "731") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "776") { return window.location.href = 'viewcart'; } else { return UiCart.delegate.modal.open(); } } if ($scope.useAnimate('add') || $scope.useAnimate('ตะกร้า') || $scope.useAnimate('order') || $scope.useAnimate('เพิ่มในรถเข็น')) { if ($scope.useAnimate('หยิบใส่ตะกร้า')) { $scope.textDisplay.cart = 'ดูตะกร้า'; } else if ($scope.useAnimate('เพิ่มในรถเข็น')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('สั่งซื้อเลย')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('order')) { $scope.textDisplay.cart = 'OPEN CART'; } else { $scope.textDisplay.cart = 'View Cart'; } var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('shown').removeClass('active').removeClass('completedAnimate'); el.addClass('shown'); var a = $timeout(function() { el.addClass('active'); $scope.animateStartOk = true; $timeout.cancel(a); var b = $timeout(function() { $timeout.cancel(b); return $scope.buyProcess(id, qty, false); }, 100); }, 100); } else if ($scope.useAnimate('buy') || $scope.useAnimate('ซื้อ')) { return $scope.buyProcess(id, qty, true); } else { return $scope.buyProcess(id, qty); } }; /* animate when finish add card */ $scope.failStack = 1; $scope.doAnimateEnd = function(id, qty) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.removeClass('finished'); e.find('.onStart').removeClass('ready').removeClass('next'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; clearClass(id); var el = $('[data-id="animate_of_' + id + '"]'); /* var _a = $interval(function () { if ($scope.checkAdded(id)) { $interval.cancel(_a);*/ var _b = $timeout(function() { $timeout.cancel(_b); el.find('.onStart').addClass('ready'); var _c = $timeout(function() { $timeout.cancel(_c); el.find('.onStart').addClass('next'); el.find('.onFinish').addClass('shown'); var _d = $timeout(function() { el.find('.onFinish').addClass('active'); $timeout.cancel(_d); var _e = $timeout(function() { $timeout.cancel(_e); el.find('.onFinish .txt').addClass('active'); el.addClass('completedAnimate'); $timeout(function() { $scope.doAnimeteFin(id); }, 100); }, 100); }, 100); }, 100); }, 300); /*} else { $scope.failStack++; if ($scope.failStack >= 10) { $interval.cancel(_a); $scope.doAnimateError(id); } } }, 1000);*/ }; /* animate on finish process */ $scope.doAnimeteFin = function(id) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.find('.onStart').removeClass('ready'); e.find('.onStart').removeClass('next'); e.find('.onFinish').removeClass('shown'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; var el = $('[data-id="animate_of_' + id + '"]'); el.addClass('finished'); var aa = $timeout(function() { /* Make Btn Disappear */ el.removeClass('active'); $timeout.cancel(aa); var _aa = $timeout(function() { $timeout.cancel(_aa); /* Remove other class */ el.removeClass('shown'); el.removeClass('completedAnimate'); $timeout.cancel(_aa); el.removeClass('finished'); clearClass(id); $scope.doSideBtnSuccess(id); }, 300); }, 100); }; /* animate on error process */ $scope.doAnimateError = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); alert("เกิดข้อผิดพลาด!\n\n- หากสินค้ามี Option ควรเลือก Option ก่อน \n\n- หากเกิดความไม่สะดวก กรุณาติดต่อเจ้าหน้าที่...\n\nขอบคุณค่ะ"); }; /* Side button on success */ $scope.doSideBtnSuccess = function(idStr) { var el = $('[data-id="side_of_' + idStr + '"]'); if (CUR_THEME.shop_id() == "500") { if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "701") { if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "598") { if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "636") { if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } }; /* check if product on process */ $scope.checkProcess = function() { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; /* check if product added */ $scope.checkAdded = function() { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; /* user click add/buy button */ $scope.onPress = function() { /* if (UiCustomerBox.delegate.get.isLogin()) { */ var checkToDetail = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; if (checkToDetail) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + $scope.id; } return window.location.href = "#/product-detail/" + $scope.id; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); /*if(!isMobile){ $scope.doAnimateStart($scope.id, _qty); } else { $scope.buyProcess($scope.id, _qty, true); } */ } /* } else { return $inloginPopup.open(); } */ }; /* buy function * @params {product_id} product id (parent product or option product) * @params {quantity} quantity to add * @params {byPassAnimate} bypass animate to skip to cart view */ $scope.buyProcess = function(product_id, quantity, byPassAnimate) { console.log("buyProcess 1", product_id, quantity); var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { console.log("buyProcess 2", product_id, quantity); console.log("buyProcess : adding", $scope.id, quantity); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid, function(e) { console.log("buyProcess: callback", e); if (e !== false) { /* check store.js */ if (typeof store !== 'undefined' && store != undefined) { store.set('gae_cart_id', e.cart_id); /* doc: https://github.com/marcuswestin/store.js */ } if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } console.log("buyProcess 2.5", product_id, quantity); /* Virtual Cart Refresh */ /* Virtual Cart Refresh */ $scope.virtualCartRefresh(); /* virtualCartRefresh */ /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return $scope.doAnimateEnd(product_id, quantity); } else { return $scope.doAnimateError(product_id); } }); } else { console.log("buyProcess 3", product_id, quantity); if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } $scope.doAnimateEnd(product_id, quantity); return UiCart.delegate.modal.open(); } } /*eturn UiCart.delegate.modal.open();*/ }; $scope.virtualCartTypeB = function(functionone, functiontwo) { var root_virtual_cart_type_b = $('#root-virtual-cart-type-b').hasClass('show'); if (!root_virtual_cart_type_b) { if (functionone == 'isCart') { return $virtualCartTypeB.isCart(); } else if (functionone == 'isLoad') { return $virtualCartTypeB.isLoad(); } } else { if (functiontwo == 'isCart') { return $virtualCartTypeB.isCart(); } else if (functiontwo == 'isLoad') { return $virtualCartTypeB.isLoad(); } } }; $scope.virtualCartRefreshIn = function() { var shop_id = $scope.currentShopId; switch (shop_id) { case 635: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCart() */ break; } }; $scope.virtualCartRefresh = function() { var shop_id = $scope.currentShopId; switch (shop_id) { case 500: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 635: $scope.virtualCartRefreshIn(); /* virtualCartRefreshIn */ break; case 718: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 414: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 699: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 717: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 723: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 741: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 728: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 737: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 401: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 740: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; default: $scope.virtualCart('fetch', 'fetch'); /* virtualCart() */ break; } }; $scope.virtualCart = function(functionone, functiontwo) { var root_virtual_cart = $('#root-virtual-cart').hasClass('is-open'); if (!root_virtual_cart) { /* open virtual cart & refresh virtual cart */ if (functionone == 'open') { return $virtualCart.open(); } else if (functionone == 'fetch') { return $virtualCart.fetch(); } } else { /* refresh virtual cart */ if (functiontwo == 'open') { return $virtualCart.open(); } else if (functiontwo == 'fetch') { return $virtualCart.fetch(); } } }; $scope.virtualCartTypeA = function(functionone, functiontwo) { var root_virtual_cart_type_a = $('#root-virtual-cart-type-a').hasClass('is-open'); if (!root_virtual_cart_type_a) { if (functionone == 'isOpenOrClose') { return $virtualCartTypeA.isOpenOrClose(); } else if (functionone == 'load') { return $virtualCartTypeA.load(); } } else { if (functiontwo == 'isOpenOrClose') { return $virtualCartTypeA.isOpenOrClose(); } else if (functiontwo == 'load') { return $virtualCartTypeA.load(); } } }; $scope.checkAddedClass = function() { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; /* Check if animate start */ $scope.animateStartOk = function() {}; /* Calculate Width Of Btn */ $scope.calWidth = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerWidth(true); }; /* Calculate Height Of Btn */ $scope.calHeight = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); }; /* Calculate margin calMarginTop Of Btn */ $scope.calMarginTop = function() { var a = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); var b = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(true); var c = a + ((b - a) / 2); return '-' + c + 'px'; }; /* Calculate margin left Of Btn */ $scope.calMarginLeft = function() { if (typeof $('[data-id="buy_of_' + $scope.id + '"]').position() !== 'undefined') { var l = $('[data-id="buy_of_' + $scope.id + '"]').position().left; return (l - 15) + 'px'; } return '0px'; }; }; return promise; });_ui_share_app.directive('componentBuyButtonF', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', btntwostyle: '@btntwostyle', fonttwostyle: '@fonttwostyle', text: '@text', wait: '@wait', view: '@view', margin: '@margin', id: '@productid', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', animatename: '@animatename', promotelink: '@promotelink', imgcart: '@imgcart', promotionid: '@promotionid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = { 'icon': '?icon', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.btntwostyle = (typeof $scope.btntwostyle == 'undefined' || $scope.btntwostyle == '') ? $scope.btnstyle : $scope.btntwostyle; $scope._use_side_promote = (typeof $scope.sidepromote !== 'undefined' && $scope.sidepromote == 'true') ? true : false; $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.promote_link = ''; $scope.promote_text = ''; $scope.temp_added_product = []; $scope.$watch('promotelink', function(newValue, oldValue) { if (!newValue || newValue == "") { return; } var a = newValue.split(","); if (a.length) { $scope.promote_link = encodeURIComponent(a[1]); $scope.promote_text = a[0]; if (CUR_THEME.shop_id() == "459") { $scope.promote_link = "#/"; $scope.promote_link = $scope.promote_link + encodeURIComponent(a[1]); } } }); $scope.currentShopId = parseInt(CUR_THEME.shop_id()); /* check text to allow something */ $scope.useAnimate = function(stringCheck) { var a = $scope.text; var b = a.toLowerCase(); if (b.indexOf(stringCheck) !== -1) { return true; } else { return false; } }; /* default text*/ $scope.textDisplay = { buy: $scope.text || 'Buy Now', wait: $scope.wait || 'Please Wait..', cart: ($scope.useAnimate('buy')) ? 'In Cart' : $scope.view || 'View Cart' }; /* animate : on click */ $scope.animateStartOk = false; $scope.doAnimateStart = function(id, qty) { /*console.log('doAnimateStart: $scope.checkAdded(id)', $scope.checkAdded(id)); console.log('doAnimateStart: $scope.useAnimate(\'buy\')', $scope.useAnimate('buy')); console.log('doAnimateStart: $scope.useAnimate(\'add\')', $scope.useAnimate('add')); console.log('doAnimateStart: $scope.useAnimate(\'shop\')', $scope.useAnimate('shop')); console.log('doAnimateStart: $scope.text', $scope.text);*/ if ($scope.checkAdded(id)) { if (CUR_THEME.shop_id() == "414") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "699") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "717") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "718") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "676") { // var pathString = 'viewcart'; return window.location.href = 'viewcart'; } else { return UiCart.delegate.modal.open(); } } if ($scope.useAnimate('add') || $scope.useAnimate('ตะกร้า') || $scope.useAnimate('order') || $scope.useAnimate('shop') || $scope.useAnimate('buy') || $scope.useAnimate('ซื้อเลย') || $scope.useAnimate('หยิบใส่ตะกร้า') || $scope.useAnimate('เพิ่มในรถเข็น')) { if ($scope.useAnimate('หยิบใส่ตะกร้า')) { $scope.textDisplay.cart = 'ดูตะกร้า'; } else if ($scope.useAnimate('เพิ่มในรถเข็น')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else { $scope.textDisplay.cart = 'View Cart'; } var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('shown').removeClass('active').removeClass('completedAnimate'); el.addClass('shown'); var a = $timeout(function() { el.addClass('active'); $scope.animateStartOk = true; $timeout.cancel(a); var b = $timeout(function() { $timeout.cancel(b); return $scope.buyProcess(id, qty, false); }, 100); }, 100); } else if ($scope.useAnimate('buy') || $scope.useAnimate('ซื้อ')) { return $scope.buyProcess(id, qty, true); } else { return $scope.buyProcess(id, qty); } }; /* animate when finish add card */ $scope.failStack = 1; $scope.doAnimateEnd = function(id, qty) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.removeClass('finished'); e.find('.onStart').removeClass('ready').removeClass('next'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; clearClass(id); var el = $('[data-id="animate_of_' + id + '"]'); /* var _a = $interval(function () { if ($scope.checkAdded(id)) { $interval.cancel(_a);*/ var _b = $timeout(function() { $timeout.cancel(_b); el.find('.onStart').addClass('ready'); var _c = $timeout(function() { $timeout.cancel(_c); el.find('.onStart').addClass('next'); el.find('.onFinish').addClass('shown'); var _d = $timeout(function() { el.find('.onFinish').addClass('active'); $timeout.cancel(_d); var _e = $timeout(function() { $timeout.cancel(_e); el.find('.onFinish .txt').addClass('active'); el.addClass('completedAnimate'); $timeout(function() { $scope.doAnimeteFin(id); }, 100); }, 100); }, 100); }, 100); }, 300); /*} else { $scope.failStack++; if ($scope.failStack >= 10) { $interval.cancel(_a); $scope.doAnimateError(id); } } }, 1000);*/ }; /* animate on finish process */ $scope.doAnimeteFin = function(id) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.find('.onStart').removeClass('ready'); e.find('.onStart').removeClass('next'); e.find('.onFinish').removeClass('shown'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; var el = $('[data-id="animate_of_' + id + '"]'); el.addClass('finished'); var aa = $timeout(function() { /* Make Btn Disappear */ el.removeClass('active'); $timeout.cancel(aa); var _aa = $timeout(function() { $timeout.cancel(_aa); /* Remove other class */ el.removeClass('shown'); el.removeClass('completedAnimate'); $timeout.cancel(_aa); el.removeClass('finished'); clearClass(id); $scope.doSideBtnSuccess(id); }, 300); }, 100); }; /* animate on error process */ $scope.doAnimateError = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); alert("เกิดข้อผิดพลาด!\n\n- หากสินค้ามี Option ควรเลือก Option ก่อน \n\n- หากเกิดความไม่สะดวก กรุณาติดต่อเจ้าหน้าที่...\n\nขอบคุณค่ะ"); }; /* Side button on success */ $scope.shopState = false; $scope.shopStateShow = false; $scope.doSideBtnSuccess = function(idStr) { var el = $('[data-id="side_of_' + idStr + '"]'); if (CUR_THEME.shop_id() == "530") { $scope.shopStateShow = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "401") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "414") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "500") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "676") { $scope.shopStateShow = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "701") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "598") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "636") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "465") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "481") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "459") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "509") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "535") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "523") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "713") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "718") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } }; /* check if product on process */ $scope.checkProcess = function() { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; /* check if product added */ $scope.checkAdded = function() { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; /* user click add/buy button */ $scope.onPress = function() { var checkToDetail = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; if (checkToDetail) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + $scope.id; } return window.location.href = "#/product-detail/" + $scope.id; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); /*if(!isMobile){ $scope.doAnimateStart($scope.id, _qty); } else { $scope.buyProcess($scope.id, _qty, true); } */ } }; /* buy function * @params {product_id} product id (parent product or option product) * @params {quantity} quantity to add * @params {byPassAnimate} bypass animate to skip to cart view */ $scope.buyProcess = function(product_id, quantity, byPassAnimate) { console.log("buyProcess 1", product_id, quantity); var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { console.log("buyProcess 2", product_id, quantity); console.log("buyProcess : adding", $scope.id, quantity); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid, function(e) { console.log("buyProcess: callback", e); if (e !== false) { if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } console.log("buyProcess 2.5", product_id, quantity); /* Virtual Cart Refresh */ if ($('.virtual-view-container').length > 0) { if (!$('#root-virtual-cart').hasClass('is-open')) { switch ($scope.currentShopId) { case 500: /* missmonribs */ /* open virtual cart & refresh virtual cart */ $virtualCart.open(); break; default: /* refresh virtual cart */ $virtualCart.fetch(); break; } } else { /* refresh virtual cart */ $virtualCart.fetch(); } } /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return $scope.doAnimateEnd(product_id, quantity); } else { return $scope.doAnimateError(product_id); } }); } else { console.log("buyProcess 3", product_id, quantity); if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } $scope.doAnimateEnd(product_id, quantity); return UiCart.delegate.modal.open(); } } /*eturn UiCart.delegate.modal.open();*/ }; $scope.checkAddedClass = function() { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; /* Check if animate start */ $scope.animateStartOk = function() {}; /* Calculate Width Of Btn */ $scope.calWidth = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerWidth(true); }; /* Calculate Height Of Btn */ $scope.calHeight = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); }; /* Calculate margin calMarginTop Of Btn */ $scope.calMarginTop = function() { var a = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); var b = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(true); var c = a + ((b - a) / 2); return '-' + c + 'px'; }; /* Calculate margin left Of Btn */ $scope.calMarginLeft = function() { if (typeof $('[data-id="buy_of_' + $scope.id + '"]').position() !== 'undefined') { var l = $('[data-id="buy_of_' + $scope.id + '"]').position().left; return (l - 30) + 'px'; } return '0px'; }; }; return promise; }); _ui_share_app.directive('componentBuyButtonG', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', btntwostyle: '@btntwostyle', fonttwostyle: '@fonttwostyle', text: '@text', wait: '@wait', view : '@view', margin: '@margin', id: '@productid', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', animatename: '@animatename', promotelink: '@promotelink', imgcart: '@imgcart', promotionid: '@promotionid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = { 'icon': '?icon', }; promise.controller = function ($scope, $timeout, $interval, $q, $window ,$location) { $scope.btntwostyle = (typeof $scope.btntwostyle == 'undefined' || $scope.btntwostyle == '') ? $scope.btnstyle : $scope.btntwostyle; $scope._use_side_promote = (typeof $scope.sidepromote !== 'undefined' && $scope.sidepromote == 'true') ? true : false; $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.promote_link = ''; $scope.promote_text = ''; $scope.temp_added_product = []; $scope.$watch('promotelink',function(newValue,oldValue){ if(!newValue || newValue == ""){ return; } var a = newValue.split(","); if(a.length){ $scope.promote_link = encodeURIComponent(a[1]); $scope.promote_text = a[0]; if(CUR_THEME.shop_id()=="459"){ $scope.promote_link = "#/"; $scope.promote_link = $scope.promote_link + encodeURIComponent(a[1]); } } }); $scope.currentShopId = parseInt(CUR_THEME.shop_id()); /* check text to allow something */ $scope.useAnimate = function (stringCheck) { var a = $scope.text; var b = a.toLowerCase(); if (b.indexOf(stringCheck) !== -1) { return true; }else { return false; } }; /* default text*/ $scope.textDisplay = { buy: $scope.text || 'Buy Now', wait: $scope.wait || 'Please Wait..', cart: ($scope.useAnimate('buy')) ? 'In Cart' : $scope.view || 'ดูรถเข็น' }; /* animate : on click */ $scope.animateStartOk = false; $scope.doAnimateStart = function (id, qty) { /*console.log('doAnimateStart: $scope.checkAdded(id)', $scope.checkAdded(id)); console.log('doAnimateStart: $scope.useAnimate(\'buy\')', $scope.useAnimate('buy')); console.log('doAnimateStart: $scope.useAnimate(\'add\')', $scope.useAnimate('add')); console.log('doAnimateStart: $scope.useAnimate(\'shop\')', $scope.useAnimate('shop')); console.log('doAnimateStart: $scope.text', $scope.text);*/ if ($scope.checkAdded(id)) { return window.location.href = 'viewcart'; } if ($scope.useAnimate('add') || $scope.useAnimate('ตะกร้า') || $scope.useAnimate('order') || $scope.useAnimate('shop') || $scope.useAnimate('buy') || $scope.useAnimate('ซื้อเลย') || $scope.useAnimate('หยิบใส่ตะกร้า') || $scope.useAnimate('เพิ่มในรถเข็น') || $scope.useAnimate('สั่งซื้อเลย') ) { if($scope.useAnimate('หยิบใส่ตะกร้า')){ $scope.textDisplay.cart = 'ดูตะกร้า'; }else if($scope.useAnimate('เพิ่มในรถเข็น')){ $scope.textDisplay.cart = 'ดูรถเข็น'; }else if($scope.useAnimate('สั่งซื้อเลย')){ $scope.textDisplay.cart = 'ดูรถเข็น'; }else if($scope.useAnimate('order')){ $scope.textDisplay.cart = 'OPEN CART'; } else{ $scope.textDisplay.cart = 'In Cart'; } var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('shown').removeClass('active').removeClass('completedAnimate'); el.addClass('shown'); var a = $timeout(function () { el.addClass('active'); $scope.animateStartOk = true; $timeout.cancel(a); var b = $timeout(function () { $timeout.cancel(b); return $scope.buyProcess(id, qty, false); }, 100); }, 100); } else if ($scope.useAnimate('buy') || $scope.useAnimate('ซื้อ')) { return $scope.buyProcess(id, qty, true); } else { return $scope.buyProcess(id, qty); } }; /* animate when finish add card */ $scope.failStack = 1; $scope.doAnimateEnd = function (id, qty) { var clearClass = function (idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.removeClass('finished'); e.find('.onStart').removeClass('ready').removeClass('next'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; clearClass(id); var el = $('[data-id="animate_of_' + id + '"]'); /* var _a = $interval(function () { if ($scope.checkAdded(id)) { $interval.cancel(_a);*/ var _b = $timeout(function () { $timeout.cancel(_b); el.find('.onStart').addClass('ready'); var _c = $timeout(function () { $timeout.cancel(_c); el.find('.onStart').addClass('next'); el.find('.onFinish').addClass('shown'); var _d = $timeout(function () { el.find('.onFinish').addClass('active'); $timeout.cancel(_d); var _e = $timeout(function () { $timeout.cancel(_e); el.find('.onFinish .txt').addClass('active'); el.addClass('completedAnimate'); $timeout(function () { $scope.doAnimeteFin(id); }, 100); }, 100); }, 100); }, 100); }, 300); /*} else { $scope.failStack++; if ($scope.failStack >= 10) { $interval.cancel(_a); $scope.doAnimateError(id); } } }, 1000);*/ }; /* animate on finish process */ $scope.doAnimeteFin = function (id) { var clearClass = function (idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.find('.onStart').removeClass('ready'); e.find('.onStart').removeClass('next'); e.find('.onFinish').removeClass('shown'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; var el = $('[data-id="animate_of_' + id + '"]'); el.addClass('finished'); var aa = $timeout(function () { /* Make Btn Disappear */ el.removeClass('active'); $timeout.cancel(aa); var _aa = $timeout(function () { $timeout.cancel(_aa); /* Remove other class */ el.removeClass('shown'); el.removeClass('completedAnimate'); $timeout.cancel(_aa); el.removeClass('finished'); clearClass(id); $scope.doSideBtnSuccess(id); }, 300); }, 100); }; /* animate on error process */ $scope.doAnimateError = function (id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); alert("เกิดข้อผิดพลาด!\n\n- หากสินค้ามี Option ควรเลือก Option ก่อน \n\n- หากเกิดความไม่สะดวก กรุณาติดต่อเจ้าหน้าที่...\n\nขอบคุณค่ะ"); }; /* Side button on success */ $scope.shopState = false; $scope.shopStateShow = false; $scope.doSideBtnSuccess = function(idStr){ var el = $('[data-id="side_of_' + idStr + '"]'); if(CUR_THEME.shop_id()=="530"){ $scope.shopStateShow = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="401"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="414"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="500"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="676"){ $scope.shopStateShow = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="701"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="598"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="636"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="465"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="481"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="459"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="509"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="535"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="523"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="713"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="718"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="699"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } }; /* check if product on process */ $scope.checkProcess = function () { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; /* check if product added */ $scope.checkAdded = function () { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; /* user click add/buy button */ $scope.onPress = function () { var checkToDetail = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; if (checkToDetail) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + $scope.id; } return window.location.href = "#/product-detail/" + $scope.id; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); /*if(!isMobile){ $scope.doAnimateStart($scope.id, _qty); } else { $scope.buyProcess($scope.id, _qty, true); } */ } }; /* buy function * @params {product_id} product id (parent product or option product) * @params {quantity} quantity to add * @params {byPassAnimate} bypass animate to skip to cart view */ $scope.buyProcess = function (product_id, quantity, byPassAnimate) { console.log("buyProcess 1", product_id, quantity); var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { console.log("buyProcess 2", product_id, quantity); console.log("buyProcess : adding", $scope.id, quantity); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid, function(e){ console.log("buyProcess: callback", e); if(e !== false){ if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } console.log("buyProcess 2.5", product_id, quantity); /* Virtual Cart Refresh */ if($('.virtual-view-container').length > 0){ if(!$('#root-virtual-cart').hasClass('is-open')){ switch($scope.currentShopId){ case 500: /* missmonribs*/ /* open virtual cart & refresh virtual cart */ $virtualCart.open(); break; default: /* refresh virtual cart */ $virtualCart.fetch(); break; } } else { /* refresh virtual cart */ $virtualCart.fetch(); } } /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return $scope.doAnimateEnd(product_id, quantity); } else { return $scope.doAnimateError(product_id); } }); } else { console.log("buyProcess 3", product_id, quantity); if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } $scope.doAnimateEnd(product_id, quantity); return UiCart.delegate.modal.open(); } } /*eturn UiCart.delegate.modal.open();*/ }; $scope.checkAddedClass = function () { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function () { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; /* Check if animate start */ $scope.animateStartOk = function () { }; /* Calculate Width Of Btn */ $scope.calWidth = function () { return $('[data-id="buy_of_' + $scope.id + '"]').outerWidth(true); }; /* Calculate Height Of Btn */ $scope.calHeight = function () { return $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); }; /* Calculate margin calMarginTop Of Btn */ $scope.calMarginTop = function () { var a = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); var b = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(true); var c = a + ((b - a) / 2); return '-' + c + 'px'; }; /* Calculate margin left Of Btn */ $scope.calMarginLeft = function () { if(typeof $('[data-id="buy_of_' + $scope.id + '"]').position() !== 'undefined'){ var l = $('[data-id="buy_of_' + $scope.id + '"]').position().left; return (l - 15) + 'px'; } return '0px'; }; $scope.newLoginregister = function(name){ window.location.href=GURL.base_url()+name; }; }; return promise; });_ui_share_app.directive('componentBuyButtonGrip', function($rootScope, $routeParams, sliderProvider, carouselData, $location) { var templateName = 'componentBuyButtonGrip'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', productid: '@productid', promotionid: '@promotionid', quantity: '@quantity', btnstyle: '@btnstyle', }; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = "componentBuyButtonGrip"; /* scope */ $scope._btnstyle = ($scope.btnstyle != 'undefined' && $scope.btnstyle != undefined && $scope.btnstyle != '') ? $scope.btnstyle : "special_filled_button_round_small"; $scope.$watch('productid', function(newD, oldD) { $scope._productid = (newD != 'undefined' && newD != undefined && newD != '') ? newD : 0; }); $scope.$watch('promotionid', function(newD, oldD) { $scope._promotionid = (newD != 'undefined' && newD != undefined && newD != '') ? newD : 0; }); $scope.$watch('quantity', function(newD, oldD) { $scope._quantity = (newD != 'undefined' && newD != undefined && newD != '') ? parseInt(newD) : 1; }); /* scope */ $scope.buyPress = function() { var getFunction = { consoleLog: function(functionName, data) { console.log($scope._component, ' : ', functionName, ' : ', data); }, checkProcess: function() { return (UiCart.delegate.product.isProgress($scope._productid)) ? true : false; }, checkAdded: function() { return (UiCart.delegate.product.isSelected($scope._productid)) ? true : false; }, checkAddedClass: function() { var _self = this; var btnstyle = $scope._btnstyle; var useSecondary = (btnstyle.indexOf('econdary') != -1) ? true : false; var dataBackgroundColor = (!useSecondary) ? "primary_darkest" : "secondary_darkest"; return (_self.checkAdded()) ? dataBackgroundColor : ""; }, addProcess: function(product_id, quantity, promotion_id, callback) { var _self = this; _self.consoleLog("addProcess : product_id", product_id); _self.consoleLog("addProcess : quantity", quantity); _self.consoleLog("addProcess : promotion_id", promotion_id); UiCart.delegate.product.add(product_id, quantity, promotion_id, function(res) { _self.consoleLog("addProcess", res); callback(res); }); }, buyProcess: function(callback) { var _self = this; var data_process = _self.checkProcess(); var data_added = _self.checkAdded(); callback(data_process, data_added); }, main: function() { var _self = this; } } return getFunction; }; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { console.log($scope._component, ' : ', functionName, ' : ', data); }, cartId: function(stores, callback) { var _self = this; var gae_cart_id = stores.get('gae_cart_id'); var state = _self.stateData(true, false); _self.consoleLog("cartId gae_cart_id", gae_cart_id); callback(gae_cart_id, state); }, cartIdUndefined: function(gae_cart_id, callback) { var _self = this; if (gae_cart_id == undefined) { gae_cart_id = 0; } callback(gae_cart_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, sumCartRowArray: function(cartRowArray, callback) { var _self = this; var total_row_array = 0; for (var i = 0; i < cartRowArray.length; i++) { total_row_array = total_row_array + parseInt(cartRowArray[i].amount); } _self.consoleLog("sumCartRowArray total_row_array", total_row_array); callback(total_row_array); }, main: function() { var _self = this; } } return getFunction; }; $scope.setData = { classIndex: 0, classSteps: [{ class: "step_0" }, { class: "step_1" }, { class: "step_2" }, { class: "step_3" }, { class: "step_4" }], classStepState: { load: false, done: false }, dataSend: { txt_product_id: 0 }, api: "cart/current", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }; $scope.onPress = function() { if (!$scope.setData.classStepState.load) { $scope.setData.classStepState = $scope.getData().stateData(true, false); if (!$scope.buyPress().checkAdded()) { $scope.setData.classIndex = 1; $scope.getData().cartId(store, function(gae_cart_id, res_state) { $scope.setData.dataArrayState = res_state; $scope.getData().cartIdUndefined(gae_cart_id, function(res_gae_cart_id) { var filter_json = {} $scope.setData.dataSend = { 'txt_cart_id': res_gae_cart_id, 'txt_filter_json': JSON.stringify(filter_json) } $scope.getData().dataSend($scope.setData.api, $scope.setData.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, res_api, res_state) { $scope.setData.ok = res_ok; $scope.setData.dataArray = res_api; $scope.setData.dataArrayState = res_state; $scope.getData().sumCartRowArray(res_api.data.cart_row_array, function(res_total_row_array) { /* buyProcess */ var sum_quantity_total_row_array = res_total_row_array + $scope._quantity; if (sum_quantity_total_row_array <= 5) { $scope.buyPress().buyProcess(function(res_process, res_added) { if (!res_process && !res_added) { $scope.buyPress().addProcess($scope._productid, $scope._quantity, $scope._promotionid, function(res) { $scope.setData.classIndex = 4; $scope.setData.classStepState = $scope.getData().stateData(false, false); }); } else { $scope.setData.classIndex = 0; $scope.setData.classStepState = $scope.getData().stateData(false, false); } }); } else { alert("ขออภัย ลูกค้าสามารถทำรายการสั่งซื้อได้รวมไม่เกิน 5 เส้น"); $scope.setData.classIndex = 0; $scope.setData.classStepState = $scope.getData().stateData(false, false); } /* buyProcess */ }); }); }); }); }); /* buyProcess */ } else { return window.location.href = 'viewcart'; } } } setTimeout(function() { $scope.buyPress().buyProcess(function(res_process, res_added) { if (res_added) { $scope.setData.classIndex = 4; } }); }, 500); }; return promise; });_ui_share_app.directive('componentBuyButtonH', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonH'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', btntwostyle: '@btntwostyle', fonttwostyle: '@fonttwostyle', note: '@note', text: '@text', wait: '@wait', view: '@view', margin: '@margin', id: '@productid', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', animatename: '@animatename', promotelink: '@promotelink', imgcart: '@imgcart', datafont: '@datafont', promotionid: '@promotionid', isaddnote: '@isaddnote', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = { 'icon': '?icon', 'loading': '?loading', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.btntwostyle = (typeof $scope.btntwostyle == 'undefined' || $scope.btntwostyle == '') ? $scope.btnstyle : $scope.btntwostyle; $scope.datacolorfont = (typeof $scope.datafont == 'undefined' || $scope.datafont == '') ? "" : $scope.datafont; // console.log("buyProcess _note :",$scope.note); $scope._note = (typeof $scope.note != 'undefined' && $scope.note != '') ? $scope.note : 0; // console.log("buyProcess _note :",$scope._note); $scope._use_side_promote = (typeof $scope.sidepromote !== 'undefined' && $scope.sidepromote == 'true') ? true : false; $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.promote_link = ''; $scope.promote_text = ''; $scope.temp_added_product = []; $scope.$watch('promotelink', function(newValue, oldValue) { if (!newValue || newValue == "") { return; } var a = newValue.split(","); if (a.length) { $scope.promote_link = encodeURIComponent(a[1]); $scope.promote_text = a[0]; if (CUR_THEME.shop_id() == "459") { $scope.promote_link = "#/"; $scope.promote_link = $scope.promote_link + encodeURIComponent(a[1]); } } }); $scope.currentShopId = parseInt(CUR_THEME.shop_id()); /* check text to allow something */ $scope.useAnimate = function(stringCheck) { var a = $scope.text; var b = a.toLowerCase(); if (b.indexOf(stringCheck) !== -1) { return true; } else { return false; } }; $scope.qty_current_size = []; $scope.bathType1 = []; $scope.bathType2 = []; $scope.bathType3 = []; $scope.bathType4 = []; $scope.bathType5 = []; // $scope.shirtSize = []; // $scope.shirtColor = []; $scope.qtyCurrentSize = function(qty) { // vm.consoleLog("qtyCurrentSize : qty : ", qty); if (qty > 0) { for (var i = 0; i < parseInt(qty); i++) { $scope.qty_current_size.push($scope.checkFormatNumber(i + 1)); } for (var i = 0; i < parseInt(qty); i++) { $scope.bathType1.push("เลือก"); $scope.bathType2.push("เลือก"); $scope.bathType3.push("เลือก"); $scope.bathType4.push("เลือก"); $scope.bathType5.push("เลือก"); // $scope.shirtSize.push("เลือก"); // $scope.shirtColor.push("เลือก"); } // vm.consoleLog("qtyCurrentSize : qty_current_size : ", vm.qty_current_size); // vm.consoleLog("qtyCurrentSize : shirtType : ", vm.shirtType); // vm.consoleLog("qtyCurrentSize : shirtSize : ", vm.shirtSize); } else { $scope.qty_current_size = [1]; $scope.bathType1 = ["เลือก"]; $scope.bathType2 = ["เลือก"]; $scope.bathType3 = ["เลือก"]; $scope.bathType4 = ["เลือก"]; $scope.bathType5 = ["เลือก"]; // $scope.shirtSize = ["เลือก"]; // $scope.shirtColor = ["เลือก"]; } } $scope.checkFormatNumber = function(num) { var i = num.toString(); var j = i % 10, k = i % 100; // if (j == 1 && k != 11) { // return "ชุดที่" + i; // } // if (j == 2 && k != 12) { // return i + "nd Runner"; // } // if (j == 3 && k != 13) { // return i + "rd Runner"; // } return "ชุดที่" + i ; }; $scope.checkFormat = function(text) { // vm.consoleLog("checkFormat : text : ", text); var returnText = text.replace(/\?/g, "_").replace(/\&/g, "_").replace(/\#/g, "_").replace(/\-/g, "_").replace(/\!/g, "_").replace(/\*/g, "_").replace(/\:/g, "_").replace(/ /g, "_"); // vm.consoleLog("checkFormat returnText : ", returnText); return returnText; }; $scope.note = ""; $scope.noteStatus = false; $scope.showNote = function(id, note, qty) { // $scope.consoleLog("showNote : ID : ", id); // vm.consoleLog("showNote : NOTE : ", note); // vm.consoleLog("showNote : QTY : ", qty); if (note == "1") { $scope.qtyCurrentSize(qty); $scope.noteStatus = false; $("#intro-" + id).addClass("active"); } else { $scope.noteStatus = true; } return $scope.noteStatus; }; $scope.popupClose = function(id) { $scope.qty_current_size = []; $scope.team = ''; var team_class = $('.select-one #team'); team_class.css('border', ''); $scope.bathType1 = []; $scope.bathType2 = []; $scope.bathType3 = []; $scope.bathType4 = []; $scope.bathType5 = []; // $scope.shirtSize = []; // $scope.shirtColor = []; $("#intro-" + id).removeClass("active"); }; $scope.checkNote = function(bathType1, bathType2, bathType3,bathType4,bathType5) { var status = false; // vm.consoleLog("checkNote : shirtType : ", shirtType); // vm.consoleLog("checkNote : shirtSize : ", shirtSize); // vm.consoleLog("checkNote : shirtColor : ", shirtColor); $scope.note = ""; if ($scope.id == '417912') { for (var i = 0; i < bathType1.length; i++) { if (bathType1[i] != 'เลือก' && bathType2[i] != 'เลือก') { status = true; var item = i + 1; $scope.note = $scope.note + "*" + $scope.qty_current_size[i] + "*" + $scope.checkFormat($scope.bathType1[i]) + "*" + $scope.checkFormat($scope.bathType2[i]) + ""; } else { status = false; break; } } var array_class = [{'class':'.select-one','data': bathType1} ,{'class':'.select-two','data': bathType2} ,{'class':'.select-three','data': bathType3},{'class':'.select-four','data': bathType4},{'class':'.select-five','data': bathType5}]; for (var i = 0; i < bathType2.length; i++) { for (var j = 0; j < array_class.length; j++) { var select = $('[data-id="' + i + '"] '+ array_class[j].class +' .select-note'); if (array_class[j].data[i] != "เลือก") {select.css('border', '2px solid green');} else {select.css('border', '2px solid red');} } } if(status){ $scope.popupClose($scope.id); var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); // alert($scope.note); } } else if ($scope.id == '101079') { for (var i = 0; i < bathType1.length; i++) { if (bathType1[i] != 'เลือก' && bathType2[i] != 'เลือก' && bathType3[i] != 'เลือก' && bathType4[i] != 'เลือก' && bathType5[i] != 'เลือก') { status = true; var item = i + 1; $scope.note = $scope.note + "*" + $scope.qty_current_size[i] + "*" + $scope.checkFormat($scope.bathType1[i]) + "*" + $scope.checkFormat($scope.bathType2[i]) + "*" + $scope.checkFormat($scope.bathType3[i]) + "*" + $scope.checkFormat($scope.bathType4[i]) + "*" + $scope.checkFormat($scope.bathType5[i]) + ""; } else { status = false; break; } } var array_class = [{'class':'.select-one','data': bathType1} ,{'class':'.select-two','data': bathType2} ,{'class':'.select-three','data': bathType3},{'class':'.select-four','data': bathType4},{'class':'.select-five','data': bathType5}]; for (var i = 0; i < bathType2.length; i++) { for (var j = 0; j < array_class.length; j++) { var select = $('[data-id="' + i + '"] '+ array_class[j].class +' .select-note'); if (array_class[j].data[i] != "เลือก") {select.css('border', '2px solid green');} else {select.css('border', '2px solid red');} } } if(status){ $scope.popupClose($scope.id); var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); // alert($scope.note); } } return status; }; // $scope.noteStatusTrue = function() { // $scope.noteStatus = true; // return $scope.noteStatus; // }; /* default text*/ $scope.textDisplay = { buy: $scope.text || 'Buy Now', wait: $scope.wait || 'Please Wait..', cart: ($scope.useAnimate('buy')) ? 'In Cart' : $scope.view || 'View Cart' }; /* animate : on click */ $scope.animateStartOk = false; $scope.doAnimateStart = function(id, qty) { /* console.log('doAnimateStart: $scope.checkAdded(id)', $scope.checkAdded(id)); console.log('doAnimateStart: $scope.useAnimate(\'buy\')', $scope.useAnimate('buy')); console.log('doAnimateStart: $scope.useAnimate(\'add\')', $scope.useAnimate('add')); console.log('doAnimateStart: $scope.useAnimate(\'shop\')', $scope.useAnimate('shop')); console.log('doAnimateStart: $scope.text', $scope.text); */ if ($scope.checkAdded(id)) { if (CUR_THEME.shop_id() == "414") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "723") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "741") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "523") { return $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "498") { return $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "528") { return $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "495") { return $scope.virtualCartRefresh(); } else if (CUR_THEME.shop_id() == "738") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "722") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "476") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "401") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "731") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "740") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "355") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "409") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "413") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "474") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "500") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "544") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "598") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "636") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "646") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "676") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "699") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "713") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "717") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "718") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "726") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "728") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "737") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "740") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "742") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "743") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "745") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "747") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "753") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "754") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else if (CUR_THEME.shop_id() == "439") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "758") { return $virtualCart.open(); } else if (CUR_THEME.shop_id() == "535") { return window.location.href = 'viewcart'; }else if (CUR_THEME.shop_id() == "767") { return window.location.href = 'viewcart'; } else if (CUR_THEME.shop_id() == "701") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ }else if (CUR_THEME.shop_id() == "550") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ }else { return UiCart.delegate.modal.open(); } } else { if ($scope.useAnimate('add') || $scope.useAnimate('ตะกร้า') || $scope.useAnimate('order') || $scope.useAnimate('shop') || $scope.useAnimate('buy') || $scope.useAnimate('ซื้อเลย') || $scope.useAnimate('หยิบใส่ตะกร้า') || $scope.useAnimate('เพิ่มในรถเข็น') || $scope.useAnimate('สั่งซื้อเลย') || $scope.useAnimate('สั่งซื้อ') || $scope.useAnimate('หยิบใส่รถเข็น')) { if ($scope.useAnimate('หยิบใส่ตะกร้า')) { $scope.textDisplay.cart = 'ดูตะกร้า'; } else if ($scope.useAnimate('เพิ่มในรถเข็น')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('สั่งซื้อเลย')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('order')) { $scope.textDisplay.cart = 'OPEN CART'; } else if ($scope.useAnimate('สั่งซื้อ')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('เพิ่มในตะกร้า')) { $scope.textDisplay.cart = 'ดูตะกร้า'; } else if ($scope.useAnimate('หยิบใส่รถเข็น')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else { $scope.textDisplay.cart = 'View Cart'; } var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('shown').removeClass('active').removeClass('completedAnimate'); el.addClass('shown'); var a = $timeout(function() { el.addClass('active'); $scope.animateStartOk = true; $timeout.cancel(a); var b = $timeout(function() { $timeout.cancel(b); return $scope.buyProcess(id, qty, false); }, 100); }, 100); } else if ($scope.useAnimate('buy') || $scope.useAnimate('ซื้อ')) { return $scope.buyProcess(id, qty, true); } else { return $scope.buyProcess(id, qty); } } }; /* animate when finish add card */ $scope.failStack = 1; $scope.doAnimateEnd = function(id, qty) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.removeClass('finished'); e.find('.onStart').removeClass('ready').removeClass('next'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; clearClass(id); var el = $('[data-id="animate_of_' + id + '"]'); /* var _a = $interval(function () { if ($scope.checkAdded(id)) { $interval.cancel(_a);*/ var _b = $timeout(function() { $timeout.cancel(_b); el.find('.onStart').addClass('ready'); var _c = $timeout(function() { $timeout.cancel(_c); el.find('.onStart').addClass('next'); el.find('.onFinish').addClass('shown'); var _d = $timeout(function() { el.find('.onFinish').addClass('active'); $timeout.cancel(_d); var _e = $timeout(function() { $timeout.cancel(_e); el.find('.onFinish .txt').addClass('active'); el.addClass('completedAnimate'); $timeout(function() { $scope.doAnimeteFin(id); }, 100); }, 100); }, 100); }, 100); }, 300); /*} else { $scope.failStack++; if ($scope.failStack >= 10) { $interval.cancel(_a); $scope.doAnimateError(id); } } }, 1000);*/ }; /* animate on finish process */ $scope.doAnimeteFin = function(id) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.find('.onStart').removeClass('ready'); e.find('.onStart').removeClass('next'); e.find('.onFinish').removeClass('shown'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; var el = $('[data-id="animate_of_' + id + '"]'); el.addClass('finished'); var aa = $timeout(function() { /* Make Btn Disappear */ el.removeClass('active'); $timeout.cancel(aa); var _aa = $timeout(function() { $timeout.cancel(_aa); /* Remove other class */ el.removeClass('shown'); el.removeClass('completedAnimate'); $timeout.cancel(_aa); el.removeClass('finished'); clearClass(id); $scope.doSideBtnSuccess(id); }, 300); }, 100); }; /* animate on error process */ $scope.doAnimateError = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); alert("เกิดข้อผิดพลาด!\n\n- หากสินค้ามี Option ควรเลือก Option ก่อน \n\n- หากเกิดความไม่สะดวก กรุณาติดต่อเจ้าหน้าที่...\n\nขอบคุณค่ะ"); }; $scope.doAnimateErrorv2 = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); }; /* Side button on success */ $scope.shopState = false; $scope.shopStateShow = false; $scope.doSideBtnSuccess = function(idStr) { var el = $('[data-id="side_of_' + idStr + '"]'); if (CUR_THEME.shop_id() == "530") { $scope.shopStateShow = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "401") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "414") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "500") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "676") { $scope.shopStateShow = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "701") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "726") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "598") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "636") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "465") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "481") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "459") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "509") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "535") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "523") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "713") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "718") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "717") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "737") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "699") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "541") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "646") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "728") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } if (CUR_THEME.shop_id() == "740") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } }; /* check if product on process */ $scope.checkProcess = function() { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; /* check if product added */ $scope.checkAdded = function() { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; /* user click add/buy button */ $scope.onPress = function() { if(!$scope.checkAdded($scope.id)){ if(!$scope.showNote($scope.id,$scope.isaddnote,$scope.qty)){ return; } } // if($scope.showNote($scope.id,$scope.isaddnote,$scope.qty)){ var checkToDetail = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; // console.log("onPress checkToDetail : ",checkToDetail); if (checkToDetail) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + $scope.id; } return window.location.href = "#/product-detail/" + $scope.id; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); /*if(!isMobile){ $scope.doAnimateStart($scope.id, _qty); } else { $scope.buyProcess($scope.id, _qty, true); } */ } }; /* buy function * @params {product_id} product id (parent product or option product) * @params {quantity} quantity to add * @params {byPassAnimate} bypass animate to skip to cart view */ $scope.buyProcess = function(product_id, quantity, byPassAnimate) { // console.log("buyProcess 1", product_id, quantity); var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { // console.log("buyProcess 2", product_id, quantity); console.log("buyProcess : adding cahecked", $scope.id, quantity, $scope.promotionid); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid, function(e) { console.log("buyProcess: callback", e); if (e !== false) { if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } /* check store.js */ if (typeof store !== 'undefined' && store != undefined) { store.set('gae_cart_id', e.cart_id); /* doc: https://github.com/marcuswestin/store.js */ } if ($scope.currentShopId == 500) { if ($('.modalpopup').hasClass('open')) { $('.modalpopup').removeClass('open'); } } // console.log("buyProcess 2.5", product_id, quantity); // console.log("buyProcess _note :",$scope._note); if ($scope._note != 0) { $("#intro" + product_id).addClass("active"); } if($scope.note){ $scope.saveProductNote(product_id); } /* Virtual Cart Refresh */ $scope.virtualCartRefresh(); /* virtualCartRefresh */ /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return $scope.doAnimateEnd(product_id, quantity); } else { switch ($scope.currentShopId) { case 701: return window.location.href = "product-detail/" + $scope.id; case 717: return $scope.doAnimateErrorv2(product_id); default: return $scope.doAnimateError(product_id); break; } } }); } else { // console.log("buyProcess 3", product_id, quantity); if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } $scope.doAnimateEnd(product_id, quantity); return UiCart.delegate.modal.open(); } } /*eturn UiCart.delegate.modal.open();*/ }; $scope.virtualCartRefresh = function() { var shop_id = $scope.currentShopId; switch (shop_id) { /* virtualCartTypeB */ case 355: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 474: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 495: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 544: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 598: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 636: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 646: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 676: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 699: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 713: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 717: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 718: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 726: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 728: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 732: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 740: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 742: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 743: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 745: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 747: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 753: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 754: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 758: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 701: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 550: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; /* virtualCartTypeB */ /* virtualCartTypeA */ case 409: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 413: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 500: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 635: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; case 737: $scope.virtualCartTypeA('isOpenOrClose', 'load'); /* virtualCartTypeA() */ break; /* virtualCartTypeA */ /* virtualCart */ case 414: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 699: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 723: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 741: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 401: $scope.virtualCart('open', 'fetch'); /* virtualCart() */ break; case 523: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 528: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; case 498: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; default: $scope.virtualCart('fetch', 'fetch'); /* virtualCart() */ break; /* virtualCart */ } }; $scope.virtualCart = function(functionone, functiontwo) { var root_virtual_cart = $('#root-virtual-cart').hasClass('is-open'); if (!root_virtual_cart) { /* open virtual cart & refresh virtual cart */ if (functionone == 'open') { return $virtualCart.open(); } else if (functionone == 'fetch') { return $virtualCart.fetch(); } } else { /* refresh virtual cart */ if (functiontwo == 'open') { return $virtualCart.open(); } else if (functiontwo == 'fetch') { return $virtualCart.fetch(); } } }; $scope.virtualCartTypeA = function(functionone, functiontwo) { var root_virtual_cart_type_a = $('#root-virtual-cart-type-a').hasClass('is-open'); if (!root_virtual_cart_type_a) { if (functionone == 'isOpenOrClose') { return $virtualCartTypeA.isOpenOrClose(); } else if (functionone == 'load') { return $virtualCartTypeA.load(); } } else { if (functiontwo == 'isOpenOrClose') { return $virtualCartTypeA.isOpenOrClose(); } else if (functiontwo == 'load') { return $virtualCartTypeA.load(); } } }; $scope.virtualCartTypeB = function(functionone, functiontwo) { var root_virtual_cart_type_b = $('#root-virtual-cart-type-b').hasClass('show'); if (!root_virtual_cart_type_b) { if (functionone == 'isCart') { return $virtualCartTypeB.isCart(); } else if (functionone == 'isLoad') { return $virtualCartTypeB.isLoad(); } } else { if (functiontwo == 'isCart') { return $virtualCartTypeB.isCart(); } else if (functiontwo == 'isLoad') { return $virtualCartTypeB.isLoad(); } } }; $scope.saveProductNote = function(id) { // alert($scope.note); var product_id = id; var product_qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; if (product_qty <= 0) { product_qty = 1; } $scope.virtualCartRefresh(); var product_note = $scope.note; if (product_note == "") { // console.log("buyProcess : saveProductNote : 1", product_note); $scope.popupClose(product_id); } else { UiCart.delegate.product.updateAmountNote(product_id, product_qty, product_note, function(e) { // console.log("buyProcess : saveProductNote : 2", e); return $scope.popupClose(product_id); }); } /* Virtual Cart Refresh */ /* virtualCartRefresh */ }; // $scope.popupClose = function(product_id) { // $("#intro" + product_id).removeClass("active"); // $('.round').val('').blur(); // }; $scope.checkAddedClass = function() { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; /* Check if animate start */ $scope.animateStartOk = function() {}; /* Calculate Width Of Btn */ $scope.calWidth = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerWidth(true); }; /* Calculate Height Of Btn */ $scope.calHeight = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); }; /* Calculate margin calMarginTop Of Btn */ $scope.calMarginTop = function() { var a = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); var b = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(true); var c = a + ((b - a) / 2); return '-' + c + 'px'; }; /* Calculate margin left Of Btn */ $scope.calMarginLeft = function() { if (typeof $('[data-id="buy_of_' + $scope.id + '"]').position() !== 'undefined') { var l = $('[data-id="buy_of_' + $scope.id + '"]').position().left; return (l - 15) + 'px'; } return '0px'; }; }; return promise; });_ui_share_app.directive('componentBuyButtonS', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonS'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', btntwostyle: '@btntwostyle', fonttwostyle: '@fonttwostyle', note: '@note', text: '@text', wait: '@wait', view: '@view', margin: '@margin', id: '@productid', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', animatename: '@animatename', promotelink: '@promotelink', imgcart: '@imgcart', promotionid: '@promotionid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = { 'icon': '?icon', 'loading': '?loading', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.btntwostyle = (typeof $scope.btntwostyle == 'undefined' || $scope.btntwostyle == '') ? $scope.btnstyle : $scope.btntwostyle; console.log("buyProcess _note :", $scope.note); $scope._note = (typeof $scope.note != 'undefined' && $scope.note != '') ? $scope.note : 0; console.log("buyProcess _note :", $scope._note); $scope._use_side_promote = (typeof $scope.sidepromote !== 'undefined' && $scope.sidepromote == 'true') ? true : false; $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.promote_link = ''; $scope.promote_text = ''; $scope.temp_added_product = []; $scope.momentJs = { getDayString: function(timestamp) { return GAEAPI.time.dateFormat("DD", timestamp); }, getMonthString: function(timestamp) { return GAEAPI.time.dateFormat("MM", timestamp); }, getYearString: function(timestamp) { return GAEAPI.time.dateFormat("YYYY", timestamp); }, getHoursString: function(timestamp) { return GAEAPI.time.dateFormat("HH", timestamp); }, getMinutesString: function(timestamp) { return GAEAPI.time.dateFormat("mm", timestamp); }, getSecondsString: function(timestamp) { return GAEAPI.time.dateFormat("ss", timestamp); }, getTimesString: function(timestamp) { return GAEAPI.time.dateFormat("D : hh : mm : ss", timestamp); } }; $scope.virtualCartTypeB = function(functionone, functiontwo) { var root_virtual_cart_type_b = $('#root-virtual-cart-type-b').hasClass('show'); if (!root_virtual_cart_type_b) { if (functionone == 'isCart') { return $virtualCartTypeB.isCart(); } else if (functionone == 'isLoad') { return $virtualCartTypeB.isLoad(); } } else { if (functiontwo == 'isCart') { return $virtualCartTypeB.isCart(); } else if (functiontwo == 'isLoad') { return $virtualCartTypeB.isLoad(); } } }; $scope.virtualCartRefresh = function() { var shop_id = $scope.currentShopId; switch (shop_id) { /* virtualCartTypeB */ case 732: $scope.virtualCartTypeB('isCart', 'isLoad'); /* virtualCartTypeB() */ break; /* virtualCartTypeB */ } }; console.log("componentBuyButtonS : ", $scope.DateHours); $scope.$watch('promotelink', function(newValue, oldValue) { if (!newValue || newValue == "") { return; } var a = newValue.split(","); if (a.length) { /*$scope.promote_link = encodeURIComponent(a[1]);*/ $scope.promote_link = a[1]; $scope.promote_text = a[0]; if (CUR_THEME.shop_id() == "459") { $scope.promote_link = "#/"; $scope.promote_link = $scope.promote_link + encodeURIComponent(a[1]); } } }); $scope.currentShopId = parseInt(CUR_THEME.shop_id()); /* check text to allow something */ $scope.useAnimate = function(stringCheck) { var a = $scope.text; var b = a.toLowerCase(); if (b.indexOf(stringCheck) !== -1) { return true; } else { return false; } }; /* default text*/ $scope.textDisplay = { buy: $scope.text || 'Buy Now', wait: $scope.wait || 'Please Wait..', cart: ($scope.useAnimate('buy')) ? 'In Cart' : $scope.view || 'View Cart' }; /* animate : on click */ $scope.animateStartOk = false; $scope.doAnimateStart = function(id, qty) { /*console.log('doAnimateStart: $scope.checkAdded(id)', $scope.checkAdded(id)); console.log('doAnimateStart: $scope.useAnimate(\'buy\')', $scope.useAnimate('buy')); console.log('doAnimateStart: $scope.useAnimate(\'add\')', $scope.useAnimate('add')); console.log('doAnimateStart: $scope.useAnimate(\'shop\')', $scope.useAnimate('shop')); console.log('doAnimateStart: $scope.text', $scope.text);*/ if ($scope.checkAdded(id)) { if (CUR_THEME.shop_id() == "732") { $scope.virtualCartRefresh(); /* virtualCartRefresh */ } else { return UiCart.delegate.modal.open(); } } else { if ($scope.useAnimate('add') || $scope.useAnimate('ตะกร้า') || $scope.useAnimate('order') || $scope.useAnimate('shop') || $scope.useAnimate('buy') || $scope.useAnimate('ซื้อเลย') || $scope.useAnimate('หยิบใส่ตะกร้า') || $scope.useAnimate('เพิ่มในรถเข็น') || $scope.useAnimate('สั่งซื้อเลย') || $scope.useAnimate('สั่งซื้อ')) { if ($scope.useAnimate('หยิบใส่ตะกร้า')) { $scope.textDisplay.cart = 'ดูรายการสั่งซื้อ'; } else if ($scope.useAnimate('เพิ่มในรถเข็น')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('สั่งซื้อเลย')) { $scope.textDisplay.cart = 'ดูรถเข็น'; } else if ($scope.useAnimate('order')) { $scope.textDisplay.cart = 'OPEN CART'; } else if ($scope.useAnimate('สั่งซื้อ')) { $scope.textDisplay.cart = 'ดูรายการสั่งซื้อ'; } else { $scope.textDisplay.cart = 'View Cart'; } var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('shown').removeClass('active').removeClass('completedAnimate'); el.addClass('shown'); var a = $timeout(function() { el.addClass('active'); $scope.animateStartOk = true; $timeout.cancel(a); var b = $timeout(function() { $timeout.cancel(b); return $scope.buyProcess(id, qty, false); }, 100); }, 100); } else if ($scope.useAnimate('buy') || $scope.useAnimate('ซื้อ')) { return $scope.buyProcess(id, qty, true); } else { return $scope.buyProcess(id, qty); } } }; /* animate when finish add card */ $scope.failStack = 1; $scope.doAnimateEnd = function(id, qty) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.removeClass('finished'); e.find('.onStart').removeClass('ready').removeClass('next'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; clearClass(id); var el = $('[data-id="animate_of_' + id + '"]'); /* var _a = $interval(function () { if ($scope.checkAdded(id)) { $interval.cancel(_a);*/ var _b = $timeout(function() { $timeout.cancel(_b); el.find('.onStart').addClass('ready'); var _c = $timeout(function() { $timeout.cancel(_c); el.find('.onStart').addClass('next'); el.find('.onFinish').addClass('shown'); var _d = $timeout(function() { el.find('.onFinish').addClass('active'); $timeout.cancel(_d); var _e = $timeout(function() { $timeout.cancel(_e); el.find('.onFinish .txt').addClass('active'); el.addClass('completedAnimate'); $timeout(function() { $scope.doAnimeteFin(id); }, 100); }, 100); }, 100); }, 100); }, 300); /*} else { $scope.failStack++; if ($scope.failStack >= 10) { $interval.cancel(_a); $scope.doAnimateError(id); } } }, 1000);*/ }; /* animate on finish process */ $scope.doAnimeteFin = function(id) { var clearClass = function(idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.find('.onStart').removeClass('ready'); e.find('.onStart').removeClass('next'); e.find('.onFinish').removeClass('shown'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; var el = $('[data-id="animate_of_' + id + '"]'); el.addClass('finished'); var aa = $timeout(function() { /* Make Btn Disappear */ el.removeClass('active'); $timeout.cancel(aa); var _aa = $timeout(function() { $timeout.cancel(_aa); /* Remove other class */ el.removeClass('shown'); el.removeClass('completedAnimate'); $timeout.cancel(_aa); el.removeClass('finished'); clearClass(id); $scope.doSideBtnSuccess(id); }, 300); }, 100); }; /* animate on error process */ $scope.doAnimateError = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); alert("เกิดข้อผิดพลาด!\n\n- หากสินค้ามี Option ควรเลือก Option ก่อน \n\n- หากเกิดความไม่สะดวก กรุณาติดต่อเจ้าหน้าที่...\n\nขอบคุณค่ะ"); }; $scope.doAnimateErrorv2 = function(id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); }; /* Side button on success */ $scope.shopState = false; $scope.shopStateShow = false; $scope.doSideBtnSuccess = function(idStr) { var el = $('[data-id="side_of_' + idStr + '"]'); if (CUR_THEME.shop_id() == "732") { $scope.shopState = true; if (!el.hasClass('active')) { el.addClass('active'); var __aa = $timeout(function() { el.addClass('shown'); $timeout.cancel(__aa); }, 100); } } }; /* check if product on process */ $scope.checkProcess = function() { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; /* check if product added */ $scope.checkAdded = function() { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; /* user click add/buy button */ $scope.onPress = function() { var checkToDetail = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; if (checkToDetail) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + $scope.id; } return window.location.href = "#/product-detail/" + $scope.id; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); /*if(!isMobile){ $scope.doAnimateStart($scope.id, _qty); } else { $scope.buyProcess($scope.id, _qty, true); } */ } }; /* buy function * @params {product_id} product id (parent product or option product) * @params {quantity} quantity to add * @params {byPassAnimate} bypass animate to skip to cart view */ $scope.buyProcess = function(product_id, quantity, byPassAnimate) { console.log("buyProcess 1", product_id, quantity); var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { console.log("buyProcess 2", product_id, quantity); console.log("buyProcess : adding", $scope.id, quantity); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid, function(e) { console.log("buyProcess: callback", e); if (e !== false) { if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } /* check store.js */ if (typeof store !== 'undefined' && store != undefined) { store.set('gae_cart_id', e.cart_id); /* doc: https://github.com/marcuswestin/store.js */ } console.log("buyProcess 2.5", product_id, quantity); console.log("buyProcess _note :", $scope._note); if ($scope._note != 0) { $("#intro" + product_id).addClass("active"); } /* Virtual Cart Refresh */ /* Virtual Cart Refresh */ $scope.virtualCartRefresh(); /* virtualCartRefresh */ /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return $scope.doAnimateEnd(product_id, quantity); } else { switch ($scope.currentShopId) { case 701: return window.location.href = "product-detail/" + $scope.id; case 717: return $scope.doAnimateErrorv2(product_id); default: return $scope.doAnimateError(product_id); break; } } }); } else { console.log("buyProcess 3", product_id, quantity); if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } $scope.doAnimateEnd(product_id, quantity); return UiCart.delegate.modal.open(); } } /*eturn UiCart.delegate.modal.open();*/ }; $scope.saveProductNote = function(id) { var product_id = id; var product_qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; if (product_qty <= 0) { product_qty = 1; } var product_note = $('#introdetail' + id).val(); $virtualCart.fetch(); if (product_note == "") { console.log("buyProcess : saveProductNote : 1", product_note); return $scope.popupClose(product_id); } else { UiCart.delegate.prod uct.updateAmountNote(product_id, product_qty, product_note, function(e) { console.log("buyProcess : saveProductNote : 2", e); return $scope.popupClose(product_id); }); } $scope.virtualCartRefresh(); }; $scope.popupClose = function(product_id) { $("#intro" + product_id).removeClass("active"); $('.round').val('').blur(); }; $scope.checkAddedClass = function() { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function() { var start = 8; var end = 23; var DateHours = (new Date()).getHours(); return [23, 0, 1, 2, 3, 4, 5, 6, 7].indexOf(DateHours) != -1; }; /* Check if animate start */ $scope.animateStartOk = function() {}; /* Calculate Width Of Btn */ $scope.calWidth = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerWidth(true); }; /* Calculate Height Of Btn */ $scope.calHeight = function() { return $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); }; /* Calculate margin calMarginTop Of Btn */ $scope.calMarginTop = function() { var a = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); var b = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(true); var c = a + ((b - a) / 2); return '-' + c + 'px'; }; /* Calculate margin left Of Btn */ $scope.calMarginLeft = function() { if (typeof $('[data-id="buy_of_' + $scope.id + '"]').position() !== 'undefined') { var l = $('[data-id="buy_of_' + $scope.id + '"]').position().left; return (l - 15) + 'px'; } return '0px'; }; }; return promise; }); _ui_share_app.directive('componentBuyButtonZ', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentBuyButtonZ'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { btnstyle: '@btnstyle', btntwostyle: '@btntwostyle', fonttwostyle: '@fonttwostyle', text: '@text', wait: '@wait', view : '@view', margin: '@margin', id: '@productid', qty: '@qty', godetail: '@godetail', requirelogin: '@requirelogin', animatename: '@animatename', promotelink: '@promotelink', imgcart: '@imgcart', promotionid: '@promotionid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = { 'icon': '?icon', 'loading': '?loading', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.btntwostyle = (typeof $scope.btntwostyle == 'undefined' || $scope.btntwostyle == '') ? $scope.btnstyle : $scope.btntwostyle; $scope._use_side_promote = (typeof $scope.sidepromote !== 'undefined' && $scope.sidepromote == 'true') ? true : false; $scope.promotionid = (typeof $scope.promotionid == 'undefined' || $scope.promotionid == '') ? 0 : $scope.promotionid; $scope.promote_link = ''; $scope.promote_text = ''; $scope.temp_added_product = []; $scope.$watch('promotelink',function(newValue,oldValue){ if(!newValue || newValue == ""){ return; } var a = newValue.split(","); if(a.length){ $scope.promote_link = encodeURIComponent(a[1]); $scope.promote_text = a[0]; if(CUR_THEME.shop_id()=="459"){ $scope.promote_link = "#/"; $scope.promote_link = $scope.promote_link + encodeURIComponent(a[1]); } } }); $scope.currentShopId = parseInt(CUR_THEME.shop_id()); /* check text to allow something */ $scope.useAnimate = function (stringCheck) { var a = $scope.text; var b = a.toLowerCase(); if (b.indexOf(stringCheck) !== -1) { return true; }else { return false; } }; /* default text*/ $scope.textDisplay = { buy: $scope.text || 'Buy Now', wait: $scope.wait || 'Please Wait..', cart: ($scope.useAnimate('buy')) ? 'In Cart' : $scope.view || 'View Cart' }; /* animate : on click */ $scope.animateStartOk = false; $scope.doAnimateStart = function (id, qty) { /*console.log('doAnimateStart: $scope.checkAdded(id)', $scope.checkAdded(id)); console.log('doAnimateStart: $scope.useAnimate(\'buy\')', $scope.useAnimate('buy')); console.log('doAnimateStart: $scope.useAnimate(\'add\')', $scope.useAnimate('add')); console.log('doAnimateStart: $scope.useAnimate(\'shop\')', $scope.useAnimate('shop')); console.log('doAnimateStart: $scope.text', $scope.text);*/ if ($scope.checkAdded(id)) { if(CUR_THEME.shop_id()=="414"){ return $virtualCart.open(); }else if(CUR_THEME.shop_id()=="699"){ return $virtualCart.open(); } else { return UiCart.delegate.modal.open(); } } if ($scope.useAnimate('add') || $scope.useAnimate('ตะกร้า') || $scope.useAnimate('order') || $scope.useAnimate('shop') || $scope.useAnimate('buy') || $scope.useAnimate('ซื้อเลย') || $scope.useAnimate('หยิบใส่ตะกร้า') || $scope.useAnimate('เพิ่มในรถเข็น') || $scope.useAnimate('สั่งซื้อเลย') ) { if($scope.useAnimate('หยิบใส่ตะกร้า')){ $scope.textDisplay.cart = 'ดูตะกร้า'; }else if($scope.useAnimate('เพิ่มในรถเข็น')){ $scope.textDisplay.cart = 'ดูรถเข็น'; }else if($scope.useAnimate('สั่งซื้อเลย')){ $scope.textDisplay.cart = 'ดูรถเข็น'; }else if($scope.useAnimate('order')){ $scope.textDisplay.cart = 'OPEN CART'; } else{ $scope.textDisplay.cart = 'View Cart'; } var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('shown').removeClass('active').removeClass('completedAnimate'); el.addClass('shown'); var a = $timeout(function () { el.addClass('active'); $scope.animateStartOk = true; $timeout.cancel(a); var b = $timeout(function () { $timeout.cancel(b); return $scope.buyProcess(id, qty, false); }, 100); }, 100); } else if ($scope.useAnimate('buy') || $scope.useAnimate('ซื้อ')) { return $scope.buyProcess(id, qty, true); } else { return $scope.buyProcess(id, qty); } }; /* animate when finish add card */ $scope.failStack = 1; $scope.doAnimateEnd = function (id, qty) { var clearClass = function (idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.removeClass('finished'); e.find('.onStart').removeClass('ready').removeClass('next'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; clearClass(id); var el = $('[data-id="animate_of_' + id + '"]'); /* var _a = $interval(function () { if ($scope.checkAdded(id)) { $interval.cancel(_a);*/ var _b = $timeout(function () { $timeout.cancel(_b); el.find('.onStart').addClass('ready'); var _c = $timeout(function () { $timeout.cancel(_c); el.find('.onStart').addClass('next'); el.find('.onFinish').addClass('shown'); var _d = $timeout(function () { el.find('.onFinish').addClass('active'); $timeout.cancel(_d); var _e = $timeout(function () { $timeout.cancel(_e); el.find('.onFinish .txt').addClass('active'); el.addClass('completedAnimate'); $timeout(function () { $scope.doAnimeteFin(id); }, 100); }, 100); }, 100); }, 100); }, 300); /*} else { $scope.failStack++; if ($scope.failStack >= 10) { $interval.cancel(_a); $scope.doAnimateError(id); } } }, 1000);*/ }; /* animate on finish process */ $scope.doAnimeteFin = function (id) { var clearClass = function (idStr) { var e = $('[data-id="animate_of_' + idStr + '"]'); e.find('.onStart').removeClass('ready'); e.find('.onStart').removeClass('next'); e.find('.onFinish').removeClass('shown'); e.find('.onFinish').removeClass('active'); e.find('.onFinish .txt').removeClass('active'); }; var el = $('[data-id="animate_of_' + id + '"]'); el.addClass('finished'); var aa = $timeout(function () { /* Make Btn Disappear */ el.removeClass('active'); $timeout.cancel(aa); var _aa = $timeout(function () { $timeout.cancel(_aa); /* Remove other class */ el.removeClass('shown'); el.removeClass('completedAnimate'); $timeout.cancel(_aa); el.removeClass('finished'); clearClass(id); $scope.doSideBtnSuccess(id); }, 300); }, 100); }; /* animate on error process */ $scope.doAnimateError = function (id) { var el = $('[data-id="animate_of_' + id + '"]'); el.removeClass('active'); el.removeClass('shown'); alert("เกิดข้อผิดพลาด!\n\n- หากสินค้ามี Option ควรเลือก Option ก่อน \n\n- หากเกิดความไม่สะดวก กรุณาติดต่อเจ้าหน้าที่...\n\nขอบคุณค่ะ"); }; /* Side button on success */ $scope.shopState = false; $scope.shopStateShow = false; $scope.doSideBtnSuccess = function(idStr){ var el = $('[data-id="side_of_' + idStr + '"]'); if(CUR_THEME.shop_id()=="530"){ $scope.shopStateShow = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="401"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="414"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="500"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="676"){ $scope.shopStateShow = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="701"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="598"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="636"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="465"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="481"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="459"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="509"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="535"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="523"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="713"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="718"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="699"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="541"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } if(CUR_THEME.shop_id()=="646"){ $scope.shopState = true; if(!el.hasClass('active')){ el.addClass('active'); var __aa = $timeout(function(){ el.addClass('shown'); $timeout.cancel(__aa); },100); } } }; /* check if product on process */ $scope.checkProcess = function () { return (UiCart.delegate.product.isProgress($scope.id)) ? true : false; }; /* check if product added */ $scope.checkAdded = function () { return (UiCart.delegate.product.isSelected($scope.id)) ? true : false; }; /* user click add/buy button */ $scope.onPress = function () { var checkToDetail = ($scope.godetail == 1 || $scope.godetail == true || $scope.godetail == 'true') ? true : false; if (checkToDetail) { if (GURL.isHtml5Mode()) { return window.location.href = "product-detail/" + $scope.id; } return window.location.href = "#/product-detail/" + $scope.id; } else { var _qty = (typeof $scope.qty === 'undefined' || $scope.qty == '' || $scope.qty == false) ? 1 : $scope.qty; var isMobile = ($(window).width()) <= 991 ? true : false; $scope.doAnimateStart($scope.id, _qty); /*if(!isMobile){ $scope.doAnimateStart($scope.id, _qty); } else { $scope.buyProcess($scope.id, _qty, true); } */ } }; /* buy function * @params {product_id} product id (parent product or option product) * @params {quantity} quantity to add * @params {byPassAnimate} bypass animate to skip to cart view */ $scope.buyProcess = function (product_id, quantity, byPassAnimate) { console.log("buyProcess 1", product_id, quantity); var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { console.log("buyProcess 2", product_id, quantity); console.log("buyProcess : adding", $scope.id, quantity); UiCart.delegate.product.add(product_id, quantity, $scope.promotionid, function(e){ console.log("buyProcess: callback", e); if(e !== false){ if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } console.log("buyProcess 2.5", product_id, quantity); /* Virtual Cart Refresh */ if($('.virtual-view-container').length > 0){ if(!$('#root-virtual-cart').hasClass('is-open')){ switch($scope.currentShopId){ case 500: /* missmonribs */ /* open virtual cart & refresh virtual cart */ $virtualCart.open(); break; case 414: /* open virtual cart & refresh virtual cart */ $virtualCart.open(); break; default: /* refresh virtual cart */ $virtualCart.fetch(); break; } } else { /* refresh virtual cart */ $virtualCart.fetch(); } } /* Pixel */ $pixelScript.event('AddToCart'); $rootScope.$broadcast('buyFinished'); return $scope.doAnimateEnd(product_id, quantity); } else { switch($scope.currentShopId){ case 701: return window.location.href = "product-detail/" + $scope.id; default: return $scope.doAnimateError(product_id); break; } } }); } else { console.log("buyProcess 3", product_id, quantity); if (typeof byPassAnimate !== 'undefined' && byPassAnimate) { return UiCart.delegate.modal.open(); } $scope.doAnimateEnd(product_id, quantity); return UiCart.delegate.modal.open(); } } /*eturn UiCart.delegate.modal.open();*/ }; $scope.checkAddedClass = function () { var btn = $scope.btnstyle; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected($scope.id)) ? color : ''; }; $scope.checkHide = function () { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; /* Check if animate start */ $scope.animateStartOk = function () { }; /* Calculate Width Of Btn */ $scope.calWidth = function () { return $('[data-id="buy_of_' + $scope.id + '"]').outerWidth(true); }; /* Calculate Height Of Btn */ $scope.calHeight = function () { return $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); }; /* Calculate margin calMarginTop Of Btn */ $scope.calMarginTop = function () { var a = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(); var b = $('[data-id="buy_of_' + $scope.id + '"]').outerHeight(true); var c = a + ((b - a) / 2); return '-' + c + 'px'; }; /* Calculate margin left Of Btn */ $scope.calMarginLeft = function () { if(typeof $('[data-id="buy_of_' + $scope.id + '"]').position() !== 'undefined'){ var l = $('[data-id="buy_of_' + $scope.id + '"]').position().left; return (l - 15); } return '0'; }; }; return promise; });_ui_share_app.factory('$componentCarousel', function componentCarousel($routeParams, $timeout) { return }); _ui_share_app.directive('componentCarouselBannerType', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCarouselBannerType'; var componentMain = 'componentCarousel'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', type: '@type', desktopsize: '@desktopsize', mobilesize: '@mobilesize', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataArray = { original: [], desktop: [], desktop_height_size: $scope.desktopsize, mobile: [], mobile_height_size: $scope.mobilesize }; $scope.dataArrayState = { load: false, done: false }; var w = angular.element($window); w.bind('resize', function() { $scope.$apply(); }); $scope.getWindow = function() { return { 'h': w.height(), 'w': w.width() }; }; $scope.$watch($scope.getWindow, function(newValue, oldValue) { var show = (newValue.w > 767) ? 'desktop' : 'mobile'; if (show == 'desktop') { $scope.carousel().jqueryAddCss('.cover_loader .table', $scope.dataArray.desktop_height_size, '1'); $scope.carousel().jqueryAddCss('.cover_loader_component_carousel_type', $scope.dataArray.desktop_height_size, '1'); $scope.carousel().jqueryAddCss('.cover_component_carousel_type .cover_image_mobile', '0', '0', 'none'); $scope.carousel().jqueryAddCss('.cover_component_carousel_type .cover_image_desktop', 'auto', '1', 'block'); } else if (show == 'mobile') { $scope.carousel().jqueryAddCss('.cover_loader .table', $scope.dataArray.mobile_height_size, '1'); $scope.carousel().jqueryAddCss('.cover_loader_component_carousel_type', $scope.dataArray.mobile_height_size, '1'); $scope.carousel().jqueryAddCss('.cover_component_carousel_type .cover_image_desktop', '0', '0', 'none'); $scope.carousel().jqueryAddCss('.cover_component_carousel_type .cover_image_mobile', 'auto', '1', 'block'); } }, true); $scope.carousel = function() { var functionIn = { image: function(cover_in, carousel_in) { var _self = this; _self.jqueryAddCss(cover_in, '0', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 2000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }).closest('section').addClass('active'); _self.jqueryAddCss(cover_in, 'auto', '1'); }, 1000); }, jqueryAddCss: function(cover_in, height, opacity, display) { $(cover_in).css('height', height); $(cover_in).css('opacity', opacity); $(cover_in).css('display', display); } } return functionIn; }; $scope.getDataArray = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, jqueryAddCss: function(cover_in, css, style) { $(cover_in).css(css, style); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getDataBadgeId: function(badgeId, badgeArray, callback) { var state = false; for (var i = 0; i < badgeArray.length; i++) { if (badgeArray[i].badge_id == badgeId) { state = true; break; } } callback(state); }, getSortBanner: function(bannerArray, callback) { var _self = this; var original = bannerArray; var desktop = []; var mobile = []; for (var i = 0; i < bannerArray.length; i++) { _self.getDataBadgeId(18, bannerArray[i].banner_badge, function(state) { if (state) { desktop.push(bannerArray[i]); } }); _self.getDataBadgeId(19, bannerArray[i].banner_badge, function(state) { if (state) { mobile.push(bannerArray[i]); } }); } callback(original, desktop, mobile); }, link: function(banner_link_url) { var _self = this; _self.consoleLog("link : banner_link_url : ", banner_link_url); if (banner_link_url != '') { if (banner_link_url.indexOf("https://") != -1 || banner_link_url.indexOf("http://")) { window.open("http://" + banner_link_url, '_blank'); } else { window.open(banner_link_url, '_blank'); } } }, main: function() { var _self = this; $scope.dataArrayState = _self.stateData(true, false); _self.getDataArray("web/home", {}, function(output) { _self.consoleLog("getDataArray : web/home : output : ", output); _self.getSortBanner(output.data.main_banner_master.banner_array, function(original, desktop, mobile) { _self.consoleLog("getDataArray : web/home : getSortBanner : original : ", original); $scope.dataArray.original = original; _self.consoleLog("getDataArray : web/home : getSortBanner : desktop : ", desktop); $scope.dataArray.desktop = desktop; _self.consoleLog("getDataArray : web/home : getSortBanner : mobile : ", mobile); $scope.dataArray.mobile = mobile; $scope.dataArrayState = _self.stateData(false, true); setTimeout(function() { _self.jqueryAddCss('.cover_loader', 'z-index', '0'); _self.jqueryAddCss('.cover_loader .table', 'opacity', '0'); }, 2000); }); }); } } return functionIn; }; $scope.getDataArray().main(); }; return promise; }); _ui_share_app.directive('componentCarouselBannerTypeA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCarouselBannerTypeA'; var componentMain = 'componentCarousel'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', callback: '@callback', mobilesize: '@mobilesize', desktopsize: '@desktopsize', componentwait: '@componentwait', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.componentWait = function() { return (typeof $scope.componentwait == 'undefined' || $scope.componentwait == '') ? 'null' : $scope.componentwait; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'mainBanner'; $scope.done = false; $scope.prev_win_size = $(window).width(); var shopIdInt = parseInt(CUR_THEME.shop_id()); GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.main_banner_master.banner_array; var dummyArray = []; var dummyArray_mobile = []; for (var i = 0; i < resultArray.length; i++) { if ($scope._showWeb(resultArray[i].banner_badge)) { dummyArray.push(resultArray[i]); } if ($scope._showApp(resultArray[i].banner_badge)) { dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; }); $scope.viewData = function() { return ($(window).width() > 767) ? $scope.data_desktop : $scope.data_mobile; }; $scope.viewDataSize = function() { return ($(window).width() > 767) ? $scope.desktopsize : $scope.mobilesize; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.resizeEvt = null; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } var a = $timeout(function() { $timeout.cancel(a); if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 1000); } }); }; $scope.checkHide = function() { return ($('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length > 0) ? true : false; }; $scope.viewLink = function(i) { $window.location.href = i; }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { return $scope.initSlider(); } }); $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size || size <= 0) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; $scope.imageIsInit = $scope.checkHide(); $scope.$watch('imageIsInit', function(newValue, oldValue) { if (!newValue) { return $('.component_carousel_lazy_container').addClass('shown'); } return $('.component_carousel_lazy_container').removeClass('shown'); }); }; return promise; });_ui_share_app.directive('componentCarouselBannerTypeB', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCarouselBannerTypeB'; var componentMain = 'componentCarousel'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', callback: '@callback', mobilesize: '@mobilesize', desktopsize: '@desktopsize', componentwait: '@componentwait', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.componentWait = function() { return (typeof $scope.componentwait == 'undefined' || $scope.componentwait == '') ? 'null' : $scope.componentwait; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'mainBannertypeb'; $scope.done = false; $scope.prev_win_size = $(window).width(); var shopIdInt = parseInt(CUR_THEME.shop_id()); GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.main_banner_master.banner_array; var dummyArray = []; var dummyArray_mobile = []; for (var i = 0; i < resultArray.length; i++) { if ($scope._showWeb(resultArray[i].banner_badge)) { dummyArray.push(resultArray[i]); } if ($scope._showApp(resultArray[i].banner_badge)) { dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; }); $scope.viewData = function() { return ($(window).width() > 767) ? $scope.data_desktop : $scope.data_mobile; }; $scope.viewDataSize = function() { return ($(window).width() > 991) ? $scope.desktopsize : $scope.height(); /* $scope.mobilesize */ }; $scope.viewDataShow = function() { return ($(window).width() > 991) ? 'desktopsize' : 'mobilesize'; }; $scope.height = function() { var height = $('.mobilesize').outerHeight(); return height + 'px'; } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.resizeEvt = null; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } var a = $timeout(function() { $timeout.cancel(a); if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 10); } }); }; $scope.checkHide = function() { return ($('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length > 0) ? true : false; }; $scope.viewLink = function(i) { $window.location.href = i; }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { return $scope.initSlider(); } }); $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size || size <= 0) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; $scope.imageIsInit = $scope.checkHide(); $scope.$watch('imageIsInit', function(newValue, oldValue) { if (!newValue) { return $('.component_carousel_lazy_container').addClass('shown'); } return $('.component_carousel_lazy_container').removeClass('shown'); }); }; return promise; });_ui_share_app.directive('componentCarouselMainTypeA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCarouselMainTypeA'; var componentMain = 'componentCarousel'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', size: '@size', pixel: '@pixel', margin: '@margin', button: '@button', iconnext: '@iconnext', iconback: '@iconback', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $http) { $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* margin seting */ $scope._margin = ($scope.margin != undefined && $scope.margin != '') ? $scope.margin : '0'; /* margin seting */ /* size seting */ $scope._size = { phones: 0, desktops: 0, pixels: "px" }; $scope._size.phones = ($scope.size != undefined && $scope.size != '') ? (parseFloat($scope.size) / 2) : 150; $scope._size.desktops = ($scope.size != undefined && $scope.size != '') ? parseFloat($scope.size) : 300; $scope._size.pixels = ($scope.pixel != undefined && $scope.pixel != '') ? $scope.pixel : 'px'; /* size seting */ /* button seting */ $scope._button = ($scope.button != undefined && $scope.button != '') ? $scope.button : 'filled_button_round_small'; /* button seting */ $scope._iconback = ($scope.iconback != undefined && $scope.iconback != '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = ($scope.iconnext != undefined && $scope.iconnext != '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { console.log('componentCarouselMainTypeA', ' : ', functionName, ' : ', data); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); callback(params, state); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getBadgeId: function(badgeArray, badgeId, callback) { var _self = this; var badge = false; for (var i = 0; i < badgeArray.length; i++) { if (badgeArray[i].badge_id == badgeId) { badge = true; break; } } callback(badge); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carousel: function(cover, carousel, carousel_id) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel + '[data-key="' + carousel_id + '"]'); carousels.not('.slick-initialized').slick({ dots: false, arrows: false, infinite: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 100); }, link: function(link) { var _self = this; if (link != '') { console.log('link : 2 ', link); window.open(link, '_blank'); } }, slickCarousel: function(carousel, index) { var _self = this; setTimeout(function() { $('[data-key="' + carousel + '"]').slick('slickGoTo', index); }, 100); } } return getFunction; }; /* carousel */ $scope.setCarousel = [{ name: "mobile", carousel: 0 }, { name: "desktop", carousel: 0 }]; $scope.getCarousel().getCarousel($scope.setCarousel[0].carousel, function(res_carousel) { $scope.setCarousel[0].carousel = res_carousel; }); $scope.getCarousel().getCarousel($scope.setCarousel[1].carousel, function(res_carousel) { $scope.setCarousel[1].carousel = res_carousel; }); /* carousel */ /* banner */ $scope.setData = { dataSend: {}, api: "web/home", ok: false, dataArray: [], dataArrayState: { load: false, done: false }, mobile: [], desktop: [] }; $scope.getData().getRouteParams(function(res_params, res_state) { $scope.setData.dataArrayState = res_state; $scope.getData().dataSend($scope.setData.api, $scope.setData.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api, res_state) { $scope.setData.ok = res_ok; $scope.setData.dataArray = get_res_api.data; var desktop = []; var mobile = []; for (var i = 0; i < get_res_api.data.main_banner.banner_array.length; i++) { desktop.push(get_res_api.data.main_banner.banner_array[i]); mobile.push(get_res_api.data.main_banner.banner_array[i]); } $scope.setData.desktop = desktop; $scope.setData.mobile = mobile; $scope.setData.dataArrayState = res_state; }); }); }); /* banner */ }; return promise; });_ui_share_app.directive('componentCarouselBanner', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselBanner'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', margin: '@margin', iconnext: '@iconnext', iconback: '@iconback', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope._margin = ($scope.margin != undefined && $scope.margin != '') ? { margin: $scope.margin } : { margin: '0 0 40px 0' }; $scope._iconback = ($scope.iconback != undefined && $scope.iconback != '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = ($scope.iconnext != undefined && $scope.iconnext != '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { console.log('componentCarouselBanner', ' : ', functionName, ' : ', data); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); callback(params, state); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getBadgeId: function(badgeArray, badgeId, callback) { var _self = this; var badge = false; for (var i = 0; i < badgeArray.length; i++) { if (badgeArray[i].badge_id == badgeId) { badge = true; break; } } callback(badge); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carousel: function(cover, carousel, carousel_id) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel + '[data-key="' + carousel_id + '"]'); carousels.not('.slick-initialized').slick({ dots: false, arrows: true, infinite: true, autoplay: true, autoplaySpeed: 4000, adaptiveHeight: true, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 100); }, link: function(link) { var _self = this; if (link != '') { console.log('link : 2 ', link); window.open(link, '_blank'); } }, slickCarousel: function(carousel, index) { var _self = this; setTimeout(function() { $('[data-key="' + carousel + '"]').slick('slickGoTo', index); }, 100); } } return getFunction; }; /* carousel */ $scope.setCarousel = [{ name: "mobile", carousel: 0 }, { name: "desktop", carousel: 0 }]; $scope.getCarousel().getCarousel($scope.setCarousel[0].carousel, function(res_carousel) { $scope.setCarousel[0].carousel = res_carousel; }); $scope.getCarousel().getCarousel($scope.setCarousel[1].carousel, function(res_carousel) { $scope.setCarousel[1].carousel = res_carousel; }); /* carousel */ /* banner */ $scope.setData = { dataSend: {}, api: "web/home", ok: false, dataArray: [], dataArrayState: { load: false, done: false }, mobile: [], desktop: [] }; $scope.getData().getRouteParams(function(res_params, res_state) { $scope.setData.dataArrayState = res_state; $scope.getData().dataSend($scope.setData.api, $scope.setData.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api, res_state) { $scope.setData.ok = res_ok; $scope.setData.dataArray = get_res_api.data; var desktop = []; var mobile = []; for (var i = 0; i < get_res_api.data.main_banner_master.banner_array.length; i++) { $scope.getData().getBadgeId(get_res_api.data.main_banner_master.banner_array[i].banner_badge, 18, function(res_badge) { if (res_badge) { desktop.push(get_res_api.data.main_banner_master.banner_array[i]); } }); $scope.getData().getBadgeId(get_res_api.data.main_banner_master.banner_array[i].banner_badge, 19, function(res_badge) { if (res_badge) { mobile.push(get_res_api.data.main_banner_master.banner_array[i]); } }); } $scope.setData.desktop = desktop; $scope.setData.mobile = mobile; $scope.setData.dataArrayState = res_state; }); }); }); /* banner */ }; return promise; });_ui_share_app.directive('setBg', function() { var templateName = 'setBg'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'A'; promise.scope = { img: '@img', other: '@other', callback: '@callback', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) { var other = (typeof scope.other !== 'undefined') ? scope.other : ''; attr.$set("style", "background-image:url(" + scope.img + ");" + other); }; return promise; }); _ui_share_app.directive('componentCarouselBannerA', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselBannerA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', margin: '@margin', callback: '@callback', imagesize: '@imagesize' }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x250_' + (i + 1) + '.jpg' }], callback_array: true }); } return r; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'mainBanner'; $scope.done = false; $scope.prev_win_size = $(window).width(); $scope.assetsPath = 'extensions/themes/assets/'; GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.main_banner_master.banner_array; if (resultArray.length <= 0) { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data_desktop = $scope.watchCallbackArray(); $scope.data_mobile = $scope.watchCallbackArray(); $scope.done = true; return; } } else { var dummyArray = []; var dummyArray_mobile = []; for (var i = 0; i < resultArray.length; i++) { if ($scope._showWeb(resultArray[i].banner_badge)) { dummyArray.push(resultArray[i]); } if ($scope._showApp(resultArray[i].banner_badge)) { dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; /*var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); */ } }); $scope.viewData = function() { return ($(window).width() > 767) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.resizeEvt = null; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } var a = $timeout(function() { $timeout.cancel(a); if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 1000); } }); }; $scope.checkHide = function() { return ($('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length > 0) ? true : false; }; $scope.viewLink = function(i) { $window.location.href = i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { return $scope.initSlider(); } }); /* Optimize image size by device pixel * @params {size} (integer) prefer size * @params {image_url} (string) original image source link * @params {image_width} (string) original image width * @return string */ $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size || size <= 0) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; $scope.imageIsInit = $scope.checkHide(); $scope.$watch('imageIsInit', function(newValue, oldValue) { if (!newValue) { return $('.component_carousel_lazy_container').addClass('shown'); } return $('.component_carousel_lazy_container').removeClass('shown'); }); }; return promise; });_ui_share_app.directive('componentCarouselBannerBa', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselBannerBa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', position: '@position', textstyle: '@textstyle', buttonstyle: '@buttonstyle', animatestyle: '@animatestyle', margin: '@margin', font: '@font', callback: '@callback', backgroundtext: '@backgroundtext', datafont: '@datafont', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'componentcarouselbannerba'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x500.gif' }], callback_array: true }); } return r; }; if (!$scope.data.length) { GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.main_banner_master.banner_array; if (resultArray.length) { /*carouselData.set($scope.type, resultArray);*/ $scope.data = resultArray; $scope.done = true; } else { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data = $scope.watchCallbackArray(); } $scope.done = true; return; } }); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 2, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: true, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: true, arrows: false, } } ]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { var a = i; if (a.indexOf('http') == -1) { return 'http://' + i; } return i; }; $scope.slickGoLeft = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); }; return promise; });_ui_share_app.directive('componentCarouselBottom', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselBottom'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', margin: '@margin', callback: '@callback', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x250_' + (i + 1) + '.jpg' }], callback_array: true }); } return r; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'carouselBottom'; $scope.done = false; $scope.prev_win_size = $(window).width(); GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.bottom_page_banner.banner_array; if (resultArray.length <= 0) { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data_desktop = $scope.watchCallbackArray(); $scope.data_mobile = $scope.watchCallbackArray(); $scope.done = true; return; } } else { var dummyArray = []; var dummyArray_mobile = []; for (var i = 0; i < resultArray.length; i++) { if ($scope._showWeb(resultArray[i].banner_badge)) { dummyArray.push(resultArray[i]); } if ($scope._showApp(resultArray[i].banner_badge)) { dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; /*var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); */ } }); var shopId = parseInt(CUR_THEME.shop_id()); $scope.viewData = function() { var breakPoint = 991; switch (shopId) { case 647: breakPoint = 767; break; default: breakPoint = 991; break; } return ($(window).width() > breakPoint) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.resizeEvt = null; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } setTimeout(function() { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function() { return ($('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length > 0) ? true : false; }; $scope.viewLink = function(i) { $window.location.href = i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); }; return promise; });_ui_share_app.directive('componentCarouselCategoryBanner', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselCategoryBanner'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', margin: '@margin', callback: '@callback', itemdata: '=datacat', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x250_' + (i + 1) + '.jpg' }], callback_array: true }); } return r; }; // console.log("carouselCategoryBanner : ",$scope.itemdata); // $scope.data = $scope.itemdata; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'carouselCategoryBanner'; $scope.done = false; $scope.prev_win_size = $(window).width(); $scope.Getdata = function(value){ console.log("carouselCategoryBanner : ",value); var resultArray = value.referral_banner_array; if (resultArray.length <= 0) { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data_desktop = $scope.watchCallbackArray(); $scope.data_mobile = $scope.watchCallbackArray(); $scope.done = true; return; } } else { var dummyArray = []; var dummyArray_mobile = []; for (var i = 0; i < resultArray.length; i++) { if (resultArray[i].banner_is_enable == '1'){ dummyArray.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; $scope.viewData(); /*var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500);*/ } }; $scope.viewData = function() { /* console.log("data caruusel top : ",$scope.data_desktop); */ return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } setTimeout(function() { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { $window.location.href = i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.$watch('itemdata', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue) { $scope.Getdata(newValue) } }); /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); }; return promise; });_ui_share_app.directive('componentCarouselMain', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMain'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', position: '@position', textstyle: '@textstyle', buttonstyle: '@buttonstyle', animatestyle: '@animatestyle', margin: '@margin', font: '@font', callback: '@callback', optimize: '@optimize', backbig: '@backbig', nextbig: '@nextbig', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'carouselMain'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; $scope.is_backbig = (typeof $scope.backbig !== 'undefined' && $scope.backbig !== "") ? $scope.backbig : 'icnt_outline_backbig01_light@2x.png'; $scope.is_nextbig = (typeof $scope.nextbig !== 'undefined' && $scope.nextbig !== "") ? $scope.nextbig : 'icnt_outline_nextbig01_light@2x.png'; $scope.is_optimize = (typeof $scope.optimize !== 'undefined' && $scope.optimize !== "") ? true : false; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x500.gif' }], callback_array: true }); } return r; }; if (!$scope.data.length) { GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.main_banner.banner_array; if (resultArray.length) { /*carouselData.set($scope.type, resultArray);*/ $scope.data = resultArray; $scope.done = true; } else { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data = $scope.watchCallbackArray(); } $scope.done = true; return; } }); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { var a = i; if (a.indexOf('http') == -1) { return 'http://' + i; } return i; }; $scope.slickGoLeft = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); $scope.viewOptimizeImage = function(size, image_url) { if (!$scope.is_optimize) { return image_url; } var a = image_url.split("/"); var b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; }; return promise; });_ui_share_app.directive('componentCarouselMainA', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMainA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', position:'@position', textstyle:'@textstyle', buttonstyle:'@buttonstyle', animatestyle:'@animatestyle', margin:'@margin', font:'@font', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'carouselMainA'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; if(!carouselData.get($scope.type) && !$scope.data.length){ GAEAPI.get('web/home', {}, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.main_banner.banner_array; if(resultArray.length){ carouselData.set($scope.type, resultArray); console.log("%ccarouselData => set state","background-color:yellow;color:black;padding:5px;"); $scope.data = resultArray; } else { $scope.done = true; return; } var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); }); } else { $scope.data = carouselData.get($scope.type); console.log("%ccarouselData => get state","background-color:yellow;color:black;padding:5px;"); var t = $interval(function () { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.initSlider(); }, 300); } }, 500); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, centerMode: true, centerPadding: '170px', slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, infinite: true, responsive: [ { breakpoint: 991, settings: { arrows: false, centerMode: true, centerPadding: '150px', slidesToShow: 1 } }, { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '30px', slidesToShow: 1 } }, { breakpoint: 480, settings: { arrows: false, dots: false, centerMode: true, centerPadding: '0px', slidesToShow: 1 } } ] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ var a = i; if(a.indexOf('http') == -1){ return 'http://'+i; } return i; }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; }; return promise; }); _ui_share_app.directive('componentCarouselMainB', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMainB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', position: '@position', textstyle: '@textstyle', buttonstyle: '@buttonstyle', animatestyle: '@animatestyle', margin: '@margin', font: '@font', callback: '@callback', backgroundtext: '@backgroundtext', currentData: '=data', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = ($scope.currentData!=undefined&&$scope.currentData) ? $scope.currentData : []; $scope.type = 'carouselMain'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x500.gif' }], callback_array: true }); } return r; }; if (!$scope.data.length) { GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.main_banner.banner_array; if (resultArray.length) { /*carouselData.set($scope.type, resultArray);*/ $scope.data = resultArray; $scope.done = true; } else { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data = $scope.watchCallbackArray(); } $scope.done = true; return; } }); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { var a = i; if (a.indexOf('http') == -1) { return 'http://' + i; } return i; }; $scope.slickGoLeft = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); }; return promise; });_ui_share_app.directive('componentCarouselMainBa', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMainBa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', position: '@position', textstyle: '@textstyle', buttonstyle: '@buttonstyle', animatestyle: '@animatestyle', margin: '@margin', font: '@font', callback: '@callback', backgroundtext: '@backgroundtext', datafont: '@datafont', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'carouselMain'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x500.gif' }], callback_array: true }); } return r; }; if (!$scope.data.length) { GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.main_banner.banner_array; if (resultArray.length) { /*carouselData.set($scope.type, resultArray);*/ $scope.data = resultArray; $scope.done = true; } else { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data = $scope.watchCallbackArray(); } $scope.done = true; return; } }); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.carousel = function(cover_in, carousel_in) { // $scope.getData().consoleLog("imageCarousel : cover_in : ", cover_in); // $scope.getData().consoleLog("imageCarousel : carousel_in :", carousel_in); $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: false, arrows: false, autoplay: true, autoplaySpeed: 5000, slidesToShow: 2, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 767, settings: { slidesToShow: 1, slidesToScroll: 1, } }] }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 1500); }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 2, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [{ breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: true, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: true, arrows: false, } }]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { var a = i; if (a.indexOf('http') == -1) { return 'http://' + i; } return i; }; $scope.slickGoLeft = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; // $rootScope.$on('repeatend', function() { // if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { // $timeout(function() { // $scope.initSlider(); // }, 500); // } // }); }; return promise; });_ui_share_app.directive('componentCarouselMainBc', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMainBc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', position: '@position', textstyle: '@textstyle', buttonstyle: '@buttonstyle', animatestyle: '@animatestyle', margin: '@margin', font: '@font', callback: '@callback', backgroundtext: '@backgroundtext', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'carouselMainBc'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x500.gif' }], callback_array: true }); } return r; }; if (!$scope.data.length) { GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.main_banner.banner_array; if (resultArray.length) { /*carouselData.set($scope.type, resultArray);*/ $scope.data = resultArray; $scope.done = true; } else { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data = $scope.watchCallbackArray(); } $scope.done = true; return; } }); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { var a = i; if (a.indexOf('http') == -1) { return 'http://' + i; } return i; }; $scope.slickGoLeft = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); }; return promise; }); _ui_share_app.directive('componentCarouselMainC', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMainC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', position:'@position', textstyle:'@textstyle', buttonstyle:'@buttonstyle', animatestyle:'@animatestyle', margin:'@margin', font:'@font', callback:'@callback', optimize:'@optimize', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'carouselMainC'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; $scope.is_optimize = (typeof $scope.optimize !== 'undefined' && $scope.optimize !== "") ? true : false; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 3; i++){ r.push({ banner_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/1000x500.gif'}], callback_array:true }); } return r; }; if(!$scope.data.length){ GAEAPI.get('web/home', {}, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.main_banner.banner_array; if(resultArray.length){ /*carouselData.set($scope.type, resultArray);*/ $scope.data = resultArray; $scope.done = true; } else { if(typeof $scope.callback !== 'undefined' && $scope.callback !== ''){ $scope.data = $scope.watchCallbackArray(); } $scope.done = true; return; } }); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, fade: true, cssEase: 'linear', variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ var a = i; if(a.indexOf('http') == -1){ return 'http://'+i; } return i; }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('.component_carousel_map[data-id="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.initSlider(); }, 500); } }); $scope.viewOptimizeImage = function(size, image_url){ if(!$scope.is_optimize){ return image_url; } var a = image_url.split("/"); var b = a[a.length - 1]; a[a.length - 1] = 't'+size+'_' + b; return a.join("/"); }; }; return promise; }); _ui_share_app.directive('componentCarouselMainD', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMainD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', position:'@position', textstyle:'@textstyle', buttonstyle:'@buttonstyle', animatestyle:'@animatestyle', margin:'@margin', font:'@font', callback:'@callback', optimize:'@optimize', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'carouselMainC'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; $scope.is_optimize = (typeof $scope.optimize !== 'undefined' && $scope.optimize !== "") ? true : false; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 3; i++){ r.push({ banner_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/1000x500.gif'}], callback_array:true }); } return r; }; if(!$scope.data.length){ GAEAPI.get('web/home', {}, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.main_banner.banner_array; if(resultArray.length){ /*carouselData.set($scope.type, resultArray);*/ $scope.data = resultArray; $scope.done = true; } else { if(typeof $scope.callback !== 'undefined' && $scope.callback !== ''){ $scope.data = $scope.watchCallbackArray(); } $scope.done = true; return; } }); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, fade: true, cssEase: 'linear', variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ var a = i; if(a.indexOf('http') == -1){ return 'http://'+i; } return i; }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('.component_carousel_map[data-id="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.initSlider(); }, 500); } }); $scope.viewOptimizeImage = function(size, image_url){ if(!$scope.is_optimize){ return image_url; } var a = image_url.split("/"); var b = a[a.length - 1]; a[a.length - 1] = 't'+size+'_' + b; return a.join("/"); }; }; return promise; }); _ui_share_app.directive('componentCarouselMainE', function($rootScope, $routeParams) { var templateName = 'componentCarouselMainE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', iconsize: '@iconsize', iconnext: '@iconnext', iconback: '@iconback', showresult: '@showresult', arrows: '@arrows', slidestoshowlarge: '@slidestoshowlarge', slidestoshowmedium: '@slidestoshowmedium', slidestoshowsmall: '@slidestoshowsmall', slidestoshowextrasmall: '@slidestoshowextrasmall', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._showresult = (typeof $scope.showresult !== 'undefined' && typeof $scope.showresult !== '') ? $scope.showresult : true; $scope._arrows = (typeof $scope.arrows !== 'undefined' && typeof $scope.arrows !== '') ? ($scope.arrows == 'true') ? true : ($scope.arrows == 'false') ? false : false : false; $scope._iconsize = (typeof $scope.iconsize !== 'undefined' && typeof $scope.iconsize !== '') ? $scope.iconsize : 30; $scope._iconback = (typeof $scope.iconback !== 'undefined' && typeof $scope.iconback !== '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = (typeof $scope.iconnext !== 'undefined' && typeof $scope.iconnext !== '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope._slidestoshowlarge = parseInt((typeof $scope.slidestoshowlarge !== 'undefined' && typeof $scope.slidestoshowlarge !== '') ? $scope.slidestoshowlarge : 4); $scope._slidestoshowmedium = parseInt((typeof $scope.slidestoshowmedium !== 'undefined' && typeof $scope.slidestoshowmedium !== '') ? $scope.slidestoshowmedium : 3); $scope._slidestoshowsmall = parseInt((typeof $scope.slidestoshowsmall !== 'undefined' && typeof $scope.slidestoshowsmall !== '') ? $scope.slidestoshowsmall : 2); $scope._slidestoshowextrasmall = parseInt((typeof $scope.slidestoshowextrasmall !== 'undefined' && typeof $scope.slidestoshowextrasmall !== '') ? $scope.slidestoshowextrasmall : 1); $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = {}; console.log('dataSend_Product', dataSend); GAEAPI.get('web/home', dataSend, $scope).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.main_banner_master.banner_array; } setTimeout(function() { $scope._dataArrayState = $scope.StateData(false, true); }, 1000); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getDataArray(); $scope.mkCarousel = function(elem) { $('.component-carousel-main-e').css('height', '0'); $('.component-carousel-main-e').css('opacity', '0'); console.log("mkCarousel : ", $scope._slidestoshowlarge, $scope._slidestoshowmedium, $scope._slidestoshowsmall, $scope._slidestoshowextrasmall); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: $scope._arrows, autoplay: true, autoplaySpeed: 4000, slidesToShow: $scope._slidestoshowlarge, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: $scope._slidestoshowmedium, } }, { breakpoint: 991, settings: { slidesToShow: $scope._slidestoshowsmall, } }, { breakpoint: 767, settings: { slidesToShow: $scope._slidestoshowextrasmall, } }] }).closest('section').addClass('active'); $('.component-carousel-main-e').css('height', 'auto'); $('.component-carousel-main-e').css('opacity', '1'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; });_ui_share_app.directive('componentCarouselMainF', function($rootScope, $routeParams) { var templateName = 'componentCarouselMainF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { buttonstyle: '@buttonstyle', size: '@size', margin: '@margin', iconsize: '@iconsize', iconnext: '@iconnext', iconback: '@iconback', showresult: '@showresult', arrows: '@arrows', slidestoshowlarge: '@slidestoshowlarge', slidestoshowmedium: '@slidestoshowmedium', slidestoshowsmall: '@slidestoshowsmall', slidestoshowextrasmall: '@slidestoshowextrasmall', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._showresult = (typeof $scope.showresult !== 'undefined' && typeof $scope.showresult !== '') ? $scope.showresult : true; $scope._arrows = (typeof $scope.arrows !== 'undefined' && typeof $scope.arrows !== '') ? ($scope.arrows == 'true') ? true : ($scope.arrows == 'false') ? false : false : false; $scope._iconsize = (typeof $scope.iconsize !== 'undefined' && typeof $scope.iconsize !== '') ? $scope.iconsize : 30; $scope._iconback = (typeof $scope.iconback !== 'undefined' && typeof $scope.iconback !== '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = (typeof $scope.iconnext !== 'undefined' && typeof $scope.iconnext !== '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope._slidestoshowlarge = parseInt((typeof $scope.slidestoshowlarge !== 'undefined' && typeof $scope.slidestoshowlarge !== '') ? $scope.slidestoshowlarge : 1); $scope._slidestoshowmedium = parseInt((typeof $scope.slidestoshowmedium !== 'undefined' && typeof $scope.slidestoshowmedium !== '') ? $scope.slidestoshowmedium : 1); $scope._slidestoshowsmall = parseInt((typeof $scope.slidestoshowsmall !== 'undefined' && typeof $scope.slidestoshowsmall !== '') ? $scope.slidestoshowsmall : 1); $scope._slidestoshowextrasmall = parseInt((typeof $scope.slidestoshowextrasmall !== 'undefined' && typeof $scope.slidestoshowextrasmall !== '') ? $scope.slidestoshowextrasmall : 1); $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope.getWebHome = function() { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = {}; console.log('getWebHome : dataSend : ', dataSend); GAEAPI.get('web/home', dataSend, $scope).then(function(output) { console.log('getWebHome : output : ', output); if (output.ok == 1) { console.log('getWebHome : output.data.main_banner.banner_array : ', output.data.main_banner.banner_array); $scope._dataArray = output.data.main_banner.banner_array; $scope._dataArrayState = $scope.StateData(false, true); } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.getWebHome(); $scope.carousel = function(elem) { $('.component-carousel-main-f').css('height', '0'); $('.component-carousel-main-f').css('opacity', '0'); console.log("carousel : ", $scope._slidestoshowlarge, $scope._slidestoshowmedium, $scope._slidestoshowsmall, $scope._slidestoshowextrasmall); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: $scope._arrows, autoplay: true, autoplaySpeed: 4000, slidesToShow: $scope._slidestoshowlarge, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: $scope._slidestoshowmedium, } }, { breakpoint: 991, settings: { slidesToShow: $scope._slidestoshowsmall, } }, { breakpoint: 767, settings: { slidesToShow: $scope._slidestoshowextrasmall, } }] }).closest('section').addClass('active'); $('.component-carousel-main-f').css('height', 'auto'); $('.component-carousel-main-f').css('opacity', '1'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.getHeightImageId = function(ImageId) { var height = $('#image_' + ImageId).height(); return height; }; }; return promise; }); _ui_share_app.directive('componentCarouselMini', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMini'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', margin:'@margin', callback:'@callback', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 6; i++){ r.push({ banner_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/180x150.jpg'}], callback_array:true }); } return r; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'carouselMini'; $scope.done = false; $scope.prev_win_size = $(window).width(); GAEAPI.get('web/home', {}, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.mini_banner.banner_array; if(resultArray.length <= 0){ if(typeof $scope.callback !== 'undefined' && $scope.callback !== ''){ $scope.data_desktop = $scope.watchCallbackArray(); $scope.data_mobile = $scope.watchCallbackArray(); $scope.done = true; return; } } else { var dummyArray = []; var dummyArray_mobile = []; for(var i = 0; i < resultArray.length; i++){ if($scope._showWeb(resultArray[i].banner_badge)){ dummyArray.push(resultArray[i]); } if($scope._showApp(resultArray[i].banner_badge)){ dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; /*var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); */ } }); $scope.viewData = function(){ return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 4, slidesToScroll: 4, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 3, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ $window.location.href=i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if($('.component_carousel_map[data-id="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.initSlider(); }, 500); } }); $scope.checkHide = function(){ return ($('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length > 0) ? true : false; }; }; return promise; }); _ui_share_app.directive('componentCarouselMiniB', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMiniB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', margin:'@margin', callback:'@callback', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 6; i++){ r.push({ banner_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/180x150.jpg'}], callback_array:true }); } return r; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'carouselMini'; $scope.done = false; $scope.prev_win_size = $(window).width(); GAEAPI.get('web/home', {}, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.mini_banner.banner_array; if(resultArray.length <= 0){ if(typeof $scope.callback !== 'undefined' && $scope.callback !== ''){ $scope.data_desktop = $scope.watchCallbackArray(); $scope.data_mobile = $scope.watchCallbackArray(); $scope.done = true; return; } } else { var dummyArray = []; var dummyArray_mobile = []; for(var i = 0; i < resultArray.length; i++){ if($scope._showWeb(resultArray[i].banner_badge)){ dummyArray.push(resultArray[i]); } if($scope._showApp(resultArray[i].banner_badge)){ dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; /*var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); */ } }); $scope.viewData = function(){ return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 3, slidesToScroll: 3, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 3, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ $window.location.href=i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if($('.component_carousel_map[data-id="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.initSlider(); }, 500); } }); $scope.checkHide = function(){ return ($('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length > 0) ? true : false; }; }; return promise; }); _ui_share_app.directive('componentCarouselMiniBox', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMiniBox'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', margin:'@margin', callback:'@callback', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 6; i++){ r.push({ banner_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/180x150.jpg'}], callback_array:true }); } return r; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'carouselMini'; $scope.done = false; $scope.prev_win_size = $(window).width(); GAEAPI.get('web/home', {}, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.mini_banner.banner_array; if(resultArray.length <= 0){ /* if(typeof $scope.callback !== 'undefined' && $scope.callback !== ''){ $scope.data_desktop = $scope.watchCallbackArray(); $scope.data_mobile = $scope.watchCallbackArray(); $scope.done = true; return; } */ } else { var dummyArray = []; var dummyArray_mobile = []; for(var i = 0; i < resultArray.length; i++){ if($scope._showWeb(resultArray[i].banner_badge)){ dummyArray.push(resultArray[i]); } if($scope._showApp(resultArray[i].banner_badge)){ dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; } }); $scope.viewData = function(){ /* console.log("data banner array box : ",$scope.data_desktop , $scope.data_mobile); */ return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 4, slidesToScroll: 4, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 3, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ $window.location.href=i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if($('.component_carousel_map[data-id="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.initSlider(); }, 500); } }); $scope.checkHide = function(){ return ($('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length > 0) ? true : false; }; /* Optimize image size by device pixel * @params {size} (integer) prefer size * @params {image_url} (string) original image source link * @params {image_width} (string) original image width * @return string */ $scope.viewOptimizeImage = function(size, image_url, image_width){ if(window.devicePixelRatio >= 2 || parseInt(image_width) <= size || size <= 0){ return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't'+size+'_' + b; return a.join("/"); }; }; return promise; }); _ui_share_app.directive('componentCarouselMiniC', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselMiniC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', margin: '@margin', callback: '@callback', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 6; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/180x150.jpg' }], callback_array: true }); } return r; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'carouselMini'; $scope.done = false; $scope.prev_win_size = $(window).width(); GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.mini_banner.banner_array; if (resultArray.length <= 0) { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data_desktop = $scope.watchCallbackArray(); $scope.data_mobile = $scope.watchCallbackArray(); $scope.done = true; return; } } else { var dummyArray = []; var dummyArray_mobile = []; for (var i = 0; i < resultArray.length; i++) { if ($scope._showWeb(resultArray[i].banner_badge)) { dummyArray.push(resultArray[i]); } if ($scope._showApp(resultArray[i].banner_badge)) { dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; /*var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); */ } }); $scope.viewData = function() { return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [{ breakpoint: 1200, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } }]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } setTimeout(function() { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { $window.location.href = i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); $scope.checkHide = function() { return ($('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length > 0) ? true : false; }; }; return promise; });_ui_share_app.directive('componentCarouselMiniSlideA', function($rootScope, $routeParams) { var templateName = 'componentCarouselMiniSlideA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margintopic: '@margintopic', margincard: '@margincard', limitdata: '@limitdata', iconsize: '@iconsize', iconnext: '@iconnext', iconback: '@iconback', showresult: '@showresult', arrows: '@arrows', slidestoshowlarge: '@slidestoshowlarge', slidestoshowmedium: '@slidestoshowmedium', slidestoshowsmall: '@slidestoshowsmall', slidestoshowextrasmall: '@slidestoshowextrasmall', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._showresult = (typeof $scope.showresult !== 'undefined' && typeof $scope.showresult !== '') ? $scope.showresult : true; $scope._arrows = (typeof $scope.arrows !== 'undefined' && typeof $scope.arrows !== '') ? ($scope.arrows == 'true') ? true : ($scope.arrows == 'false') ? false : false : false; $scope._iconsize = (typeof $scope.iconsize !== 'undefined' && typeof $scope.iconsize !== '') ? $scope.iconsize : 30; $scope._iconback = (typeof $scope.iconback !== 'undefined' && typeof $scope.iconback !== '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = (typeof $scope.iconnext !== 'undefined' && typeof $scope.iconnext !== '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope._slidestoshowlarge = parseInt((typeof $scope.slidestoshowlarge !== 'undefined' && typeof $scope.slidestoshowlarge !== '') ? $scope.slidestoshowlarge : 4); $scope._slidestoshowmedium = parseInt((typeof $scope.slidestoshowmedium !== 'undefined' && typeof $scope.slidestoshowmedium !== '') ? $scope.slidestoshowmedium : 3); $scope._slidestoshowsmall = parseInt((typeof $scope.slidestoshowsmall !== 'undefined' && typeof $scope.slidestoshowsmall !== '') ? $scope.slidestoshowsmall : 2); $scope._slidestoshowextrasmall = parseInt((typeof $scope.slidestoshowextrasmall !== 'undefined' && typeof $scope.slidestoshowextrasmall !== '') ? $scope.slidestoshowextrasmall : 1); $scope.dataMiniBanner = []; $scope.dataMiniBannerState = { load: true, done: false }; $scope.getWebHome = function() { $scope.dataMiniBannerState = $scope.StateData(true, false); var dataSend = {}; console.log('getWebHome : dataSend : ', dataSend); GAEAPI.get('web/home', dataSend).then(function(output) { if (output.ok == 1) { $scope.dataMiniBanner = output.data.mini_banner.banner_array; console.log('getWebHome : dataMiniBanner : ', $scope.dataMiniBanner); } setTimeout(function() { $scope.dataMiniBannerState = $scope.StateData(false, true); }, 1000); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.getWebHome(); $scope.mkCarousel = function(elem) { $('.component-carousel-mini-slide-a').css('height', '0'); $('.component-carousel-mini-slide-a').css('opacity', '0'); console.log("mkCarousel : ", $scope._slidestoshowlarge, $scope._slidestoshowmedium, $scope._slidestoshowsmall, $scope._slidestoshowextrasmall); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: $scope._arrows, autoplay: true, centerMode: false, variableWidth: false, autoplaySpeed: 4000, slidesToShow: $scope._slidestoshowlarge, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: $scope._slidestoshowmedium, } }, { breakpoint: 991, settings: { slidesToShow: $scope._slidestoshowsmall, } }, { breakpoint: 767, settings: { slidesToShow: $scope._slidestoshowextrasmall, } }] }).closest('section').addClass('active'); $('.component-carousel-mini-slide-a').css('height', 'auto'); $('.component-carousel-mini-slide-a').css('opacity', '1'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; }); _ui_share_app.directive('componentCarouselReferral', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCarouselReferral'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', margin:'@margin', typeid:'@typeid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.data = []; $scope.getData = function(typeId){ var d = { 'txt_referral_type_id': typeId, 'txt_sortby':'referral_lastest_create' }; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok==1){ $scope.data = e.data; } }); }; if(!$scope.data.length){ $scope.getData($scope.typeid); } /* Return difference data by window width */ $scope.viewData = function(){ return $scope.data; /*return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile;*/ }; /* Init slider */ $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 5, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 1200, settings: { slidesToShow: 4, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 3, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); /*angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } });*/ }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /** * Check if seo */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { $timeout(function(){ $scope.initSlider(); }, 300); }); $scope.type = function(){ switch($scope.typeid){ case 12: return 'brand'; break; case 17: return 'manufacturer'; break; case 18: return 'vendor'; break; default: return 'brand'; break; } }; }; return promise; }); _ui_share_app.directive('componentCarouselSecondary', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselSecondary'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', position: '@position', textstyle: '@textstyle', buttonstyle: '@buttonstyle', animatestyle: '@animatestyle', margin: '@margin', font: '@font', callback: '@callback', iconnext: '@iconnext', iconback: '@iconback', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._iconnext = (typeof $scope.iconnext !== 'undefined' && $scope.iconnext !== '') ? $scope.iconnext : 'icnt_outline_nextbig01_light@2x.png'; $scope._iconback = (typeof $scope.iconback !== 'undefined' && $scope.iconback !== '') ? $scope.iconback : 'icnt_outline_backbig01_light@2x.png'; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x500.gif' }], callback_array: true }); } return r; }; $scope.data = []; $scope.type = 'carouselSecondary'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; if (!$scope.data.length) { GAEAPI.get('web/home', {}, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.secondary_carousel.banner_array; if (resultArray.length) { $scope.data = resultArray; } else { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data = $scope.watchCallbackArray(); } $scope.done = true; document.getElementsByClassName("component_carousel_nav")[0].style.display = "none"; } $scope.done = true; /*var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500);*/ }); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { var a = i; if (a.indexOf('http') == -1) { return 'http://' + i; } return i; }; $scope.slickGoLeft = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); }; return promise; }); _ui_share_app.directive('componentCarouselTop', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCarouselTop'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', margin: '@margin', callback: '@callback', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 3; i++) { r.push({ banner_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/1000x250_' + (i + 1) + '.jpg' }], callback_array: true }); } return r; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'carouselTop'; $scope.done = false; $scope.prev_win_size = $(window).width(); GAEAPI.get('web/home', {}, $scope).then(function(res) { console.log("web/home", res); if (res.ok != 1) { return; } var resultArray = res.data.top_page_banner.banner_array; if (resultArray.length <= 0) { // alert("ss"); /* if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.data_desktop = $scope.watchCallbackArray(); $scope.data_mobile = $scope.watchCallbackArray(); $scope.done = true; return; } */ } else { // alert("ss"); var dummyArray = []; var dummyArray_mobile = []; for (var i = 0; i < resultArray.length; i++) { if ($scope._showWeb(resultArray[i].banner_badge)) { dummyArray.push(resultArray[i]); } if ($scope._showApp(resultArray[i].banner_badge)) { dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; /*var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500);*/ } }); $scope.viewData = function() { /* console.log("data caruusel top : ",$scope.data_desktop); */ return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } setTimeout(function() { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { $window.location.href = i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); }; return promise; }); _ui_share_app.factory('$componentCategory', function componentCategory($routeParams, $timeout) { return });_ui_share_app.directive('componentCategoryBadgeIdTypeA', function($rootScope, $routeParams) { var templateName = 'componentCategoryBadgeIdTypeA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', margin: '@margin', typeid: '@typeid', badgeid: '@badgeid', paddtopbottom: '@paddtopbottom', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(typeid, badgeid) { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = { 'badge_id_array': [badgeid] }; var dataSend = { 'txt_referral_type_id': typeid, 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('referral/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; if ($scope._dataArray.length > 0) { angular.forEach($scope._dataArray, function(v, k) { var product_json = { 'referral_id_array': [v.referral_id] } var dataSendProduct = { 'cur_page': 1, 'per_page': 6, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(product_json) }; GAEAPI.get('product/lists', dataSendProduct, $scope).then(function(res) { if (res.ok == 1) { if (res.data.dataList.length > 0) { $scope._dataArray[k].productList = res.data.dataList; } } }); }); } } else { $scope._dataArray = []; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.typeid, $scope.badgeid); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentCategoryBannerSildeIdA', function($rootScope, $routeParams) { var templateName = 'componentCategoryBannerSildeIdA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referralid: '@referralid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarouselData = function(elem) { console.debug('mkCarouselData: trigger'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1199, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 2, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._dataArray = []; $scope._dataArrayDone = false; $scope._getDataArray = function(id) { var dataSend = { 'txt_referral_id': id }; GAEAPI.get('referral/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; console.log("_dataArray", $scope._dataArray); } }); }; $scope._getDataArray($scope.referralid); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } }; return promise; });_ui_share_app.directive('componentCategoryFeaturedSildeA', function($rootScope, $routeParams, $location) { var templateName = 'componentCategoryFeaturedSildeA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.carousel = function(cover_in, carousel_in) { $scope.getData().consoleLog("imageCarousel : cover_in : ", cover_in); $scope.getData().consoleLog("imageCarousel : carousel_in :", carousel_in); $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: false, arrows: false, autoplay: true, autoplaySpeed: 5000, slidesToShow: 4, slidesToScroll: 4, infinite: true, prevArrow: '', nextArrow: '', speed: 600, responsive: [{ breakpoint: 1199, settings: { slidesToShow: 4, slidesToScroll: 4, } }, { breakpoint: 991, settings: { slidesToShow: 3, slidesToScroll: 3, } }, { breakpoint: 767, settings: { slidesToShow: 2, slidesToScroll: 2, } }] }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 1500); }; $scope.getData = function() { var data = { consoleLog: function(name, data) { /* console.log(name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(number, api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(number, api, dataSend); }, getApi: function(number, api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(number, output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrlProductDetail: function(product_id, product_title) { var _self = this; var url = 'product-detail/'; url += product_id + '-'; url += _self.titleUrl(product_title); _self.locationUrl(url, ''); }, locationUrl: function(url) { if (url != "") { $location.url(url).replace(); } }, windowLocation: function(url) { if (url != "") { window.location.href = url; } }, main: function() { var _self = this; } } return data; }; $scope.dataArray = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataSet = [{ number: 0, api: "referral/lists", dataSend: { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 5, 'txt_sortby': 'referral_sort_index_asc_time_desc', 'txt_filter_json': JSON.stringify({ "badge_id_array": [16] }) }, }, { number: 1, api: "product/lists", dataSend: {}, }]; $scope.getData().dataSend($scope.dataSet[0].number, $scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(number, api, dataSend) { $scope.dataArrayState = $scope.getData().stateData(true, false); $scope.getData().getApi(0, api, dataSend, function(number, output) { $scope.dataArray = output.data.dataList; $scope.dataArrayState = $scope.getData().stateData(false, true); $scope.getData().consoleLog("getData : dataArray : ", $scope.dataArray); for (var a = 0; a < output.data.dataList.length; a++) { $scope.dataArray[a].referral_product_carousel = a; $scope.dataArray[a].referral_product_state = $scope.getData().stateData(true, false); $scope.dataArray[a].referral_products = []; var filter_json = { referral_id_array: [output.data.dataList[a].referral_id], } $scope.dataSet[1].dataSend = { 'cur_page': 1, 'per_page': 8, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) } $scope.getData().dataSend(a, $scope.dataSet[1].api, $scope.dataSet[1].dataSend, function(a, api, dataSend) { $scope.getData().getApi(a, api, dataSend, function(number, output) { $scope.dataArray[number].referral_products = output.data.dataList; $scope.dataArray[a].referral_product_state = $scope.getData().stateData(false, true); $scope.getData().consoleLog("getData : dataSend to getApi to for : ", "------- dataSet.dataArray -------"); $scope.getData().consoleLog("getData : a : ", a); $scope.getData().consoleLog("getData : product_lists : ", $scope.dataArray[number].referral_products); $scope.getData().consoleLog("getData : dataSend to getApi to for : ", "------- dataSet.dataArray -------"); $scope.getData().consoleLog("getData : dataArray : ", $scope.dataArray); }); }); } }); }); }; return promise; });_ui_share_app.directive('componentCategoryFeaturedTabsTypeA', function($rootScope, $routeParams, $location) { var templateName = 'componentCategoryFeaturedTabsTypeA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var data = { consoleLog: function(name, data) { /* console.log(name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(number1, number2, api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : number1 : ", number1); _self.consoleLog("getData : number2 : ", number2); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(number1, number2, api, dataSend); }, getApi: function(number1, number2, api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : number1 : ", number1); _self.consoleLog("getData : number2 : ", number2); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(number1, number2, output); }); }, main: function() { var _self = this; }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrlProductDetail: function(product_id, product_title) { var _self = this; var url = 'product-detail/'; url += product_id + '-'; url += _self.titleUrl(product_title); _self.locationUrl(url, ''); }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, getHeight: function() { return ($(window).width() > 767) ? 100 : 60; } } return data; }; $scope.buy = function() { var data = { buyProcess: function(product_id, product_total_stock) { var _self = this; if (product_total_stock != '0') { _self.isSelected(product_id, function(selected) { console.log("buy : buyProcess : isSelected : ", selected); if (!selected) { _self.isProgress(product_id, function(progress) { console.log("buy : buyProcess : isProgress : ", progress); if (!progress) { var root_virtual_cart_type_b = $('#root-virtual-cart-type-b').hasClass('show'); if (!root_virtual_cart_type_b) { $virtualCartTypeB.isCart(); } else { $virtualCartTypeB.isLoad(); } UiCart.delegate.product.add(product_id, 1, 0, function(output) { console.log("buy : buyProcess : add : ", output); if (!root_virtual_cart_type_b) { $virtualCartTypeB.isCart(); } else { $virtualCartTypeB.isLoad(); } }); } }); } }); } else { alert("สินค้าหมดแล้วนะค่ะ"); } }, isSelected: function(product_id, callback) { var selected = UiCart.delegate.product.isSelected(product_id); callback(selected); }, isProgress: function(product_id, callback) { var progress = UiCart.delegate.product.isProgress(product_id); callback(progress); } } return data; }; $scope.tags = { index: '0' }; $scope.dataArray = []; $scope.dataSet = [{ api: "referral/short_lists", dataSend: { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 10, 'txt_badge_id': 16, 'txt_parent_id': 0, 'txt_sortby': 'referral_sort_index_asc_time_desc', }, }, { api: "referral/map", dataSend: {}, }, { api: "product/lists", dataSend: {}, }]; $scope.getData().dataSend(0, 0, $scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(number1, number2, api, dataSend) { $scope.getData().getApi(number1, number2, api, dataSend, function(number1, number2, output) { $scope.dataArray = output.data.dataList; $scope.getData().consoleLog("getData : dataArray : ", $scope.dataArray); for (var a = 0; a < output.data.dataList.length; a++) { $scope.getData().getRouteParams(function(params) { if (typeof params.root_id != 'undefined') { $scope.tags.index = params.root_id.toString(); } else { $scope.tags.index = output.data.dataList[0].referral_id.toString(); } }); $scope.dataArray[a].referral_sub_array_state = $scope.getData().stateData(true, false); $scope.dataArray[a].referral_sub_array = []; $scope.getData().consoleLog("getData : dataSend to getApi to for : ", "------- dataSet.dataArray -------"); $scope.getData().consoleLog("getData : number : ", a); $scope.getData().consoleLog("getData : referral_id : ", output.data.dataList[a].referral_id); $scope.getData().consoleLog("getData : dataSend to getApi to for : ", "------- dataSet.dataArray -------"); $scope.dataSet[1].dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': output.data.dataList[a].referral_id } $scope.getData().dataSend(a, 0, $scope.dataSet[1].api, $scope.dataSet[1].dataSend, function(number1, number2, api, dataSend) { $scope.getData().getApi(number1, number2, api, dataSend, function(number1, number2, output) { $scope.dataArray[number1].referral_sub_array = output.data; $scope.dataArray[number1].referral_sub_array_state = $scope.getData().stateData(false, true); $scope.getData().consoleLog("getData : dataSend to getApi to for : ", "------- dataSet.dataArray -------"); $scope.getData().consoleLog("getData : number1 : ", number1); $scope.getData().consoleLog("getData : referral_sub_array : ", $scope.dataArray[number1].referral_sub_array); $scope.getData().consoleLog("getData : dataSend to getApi to for : ", "------- dataSet.dataArray -------"); for (var b = 0; b < output.data.length; b++) { $scope.dataArray[number1].referral_sub_array[b].product_state = $scope.getData().stateData(true, false); $scope.dataArray[number1].referral_sub_array[b].product_list = []; $scope.getData().consoleLog("getData : dataSend to getApi to for : for : ", "------- dataSet.dataArray -------"); $scope.getData().consoleLog("getData : number2 : ", b); $scope.getData().consoleLog("getData : referral_id : ", output.data[b].referral_id); $scope.getData().consoleLog("getData : dataSend to getApi to for : for : ", "------- dataSet.dataArray -------"); var filter_json = { "referral_id_array": [output.data[b].referral_id], } $scope.dataSet[2].dataSend = { 'cur_page': 1, 'per_page': 200, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) } $scope.getData().dataSend(number1, b, $scope.dataSet[2].api, $scope.dataSet[2].dataSend, function(number1, number2, api, dataSend) { $scope.getData().getApi(number1, number2, api, dataSend, function(number1, number2, output) { $scope.getData().consoleLog("getData : getApi : output : ", output); $scope.dataArray[number1].referral_sub_array[number2].product_list = output.data.dataList; $scope.dataArray[number1].referral_sub_array[number2].product_state = $scope.getData().stateData(false, true); $scope.getData().consoleLog("getData : dataSend to getApi to for : ", "------- dataSet.dataArray -------"); $scope.getData().consoleLog("getData : number1 : ", number1); $scope.getData().consoleLog("getData : number2 : ", number2); $scope.getData().consoleLog("getData : product_list : ", $scope.dataArray[number1].referral_sub_array[number2].product_list); $scope.getData().consoleLog("getData : dataSend to getApi to for : ", "------- dataSet.dataArray -------"); $scope.getData().getRouteParams(function(params) { if (typeof params.referral_id != 'undefined' && typeof params.referral_id != '0') { $timeout(function() { $('html, body').animate({ scrollTop: $("div[id='" + params.referral_id + "']").offset().top - $scope.getData().getHeight() }, 200); }, 1000); } }); }); }); } }); }); } }); }); }; return promise; });_ui_share_app.directive('componentCategoryFeaturedTabsTypeB', function($rootScope, $routeParams, $location) { var templateName = 'componentCategoryFeaturedTabsTypeB'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('componentCategoryFeaturedTabsTypeB : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(load, done) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : load : ", load); _self.consoleLog("getData : done : ", done); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: load, done: done }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template) { $location.url(template).replace(); }, categoryUrl: function(rootId, referralId) { var _self = this; var template = "category-lists"; var res_template = template.concat("?root_id=", rootId, "&referral_id=", referralId, "&referral_type=category"); _self.locationUrl(res_template); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = "products"; $scope.state = ""; $scope.dataArrayMain = []; $scope.dataArrayMainState = $scope.getData().stateData(false, false); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.routeParams = params; $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "products"; $scope.state = "main_category"; var txt_filter_json = { badge_id_array: [16, 18] }; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_desc', 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.dataArrayMainState = $scope.getData().stateData(true, false); $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayMainState = $scope.getData().stateData(false, true); for (var i = 0; i < output.data.length; i++) { var loop = 0; var txt_filter_json = {}; var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': output.data[i].referral_id, 'txt_sortby': 'referral_sort_index_asc_name_desc', 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.dataArrayState = $scope.getData().stateData(true, false); $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(res_output) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(res_output.data); loop = loop + 1; if (output.data.length == loop) { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); }); } }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { console.log("referral/id : output.data : ", output.data); $scope.cover_top = output.data.referral_name; }); }); var txt_filter_json = { 'badge_id_array': [16, 18] }; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_desc', 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.dataArrayMainState = $scope.getData().stateData(true, false); $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayMainState = $scope.getData().stateData(false, true); }); }); var txt_filter_json = {}; var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_desc', 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.dataArrayState = $scope.getData().stateData(true, false); $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); var txt_filter_json = { 'badge_id_array': [16, 18] }; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_desc', 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.dataArrayMainState = $scope.getData().stateData(true, false); $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayMainState = $scope.getData().stateData(false, true); }); }); $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); }; return promise; });_ui_share_app.directive('componentCategoryFeaturedTabsTypeBp', function($rootScope, $routeParams, $location) { var templateName = 'componentCategoryFeaturedTabsTypeBp'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', referralid: '@referralid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = { name: "componentCategoryFeaturedTabsTypeBp", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._margin = ($scope.margin != undefined && $scope.margin != "") ? { margin: $scope.margin } : { margin: 0 }; $scope._limit = ($scope.limit != undefined && $scope.limit != "") ? parseInt($scope.limit) : 1; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getBlogId: function(params, callback) { var _self = this; var blog_id = (params.blog_id != undefined) ? params.blog_id.split("-", 1).join("") : false; _self.consoleLog("getBlogId", "blog_id", blog_id); callback(blog_id); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, getDate: function(locale, format, lifetime, callback) { var _self = this; locale = (locale == '') ? 'en' : locale; format = (format == '') ? 'LL' : format; lifetime = (lifetime != "-1" && lifetime != "") ? lifetime : ""; if (lifetime != "") { moment.locale(locale); lifetime = moment.unix(parseInt(lifetime)).format(format); } _self.consoleLog("getDate", "lifetime", lifetime); callback(lifetime); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, getCur: function(index, total, show, start, end, callback) { var _self = this; if (index == 1 && total > show) { end = show; } else if (index == total && total > show) { start = total - (show - 1); } else if (index < show && index <= (show / 2) && total > show) { end = show; } else if (index > (show / 2) && (index + (show / 2)) <= total && total > show) { start = (index - ((show / 2) - 1)); end = (index + ((show / 2))); } else if (index < total && total > show) { start = total - (show - 1); } _self.getCurArray(start, end, function(res_cur_page_array) { _self.consoleLog("getCur", "res_cur_page_array", res_cur_page_array); callback(res_cur_page_array); }); }, getCurArray: function(start, end, callback) { var _self = this; var cur_page_array = []; for (var i = start; i <= end; i++) { var item = { state: true, number: i } cur_page_array.push(item); } _self.consoleLog("getCurArray", "cur_page_array", cur_page_array); callback(cur_page_array); }, getCurPageArray: function(curPage, perPage, totalRows, callback) { var _self = this; var show = 6; var cur_pages = Math.round(totalRows / perPage); var cur_page_array = []; var cur = { start: 1, end: cur_pages } _self.getCur(curPage, cur_pages, show, cur.start, cur.end, function(res_cur_page_array) { cur_page_array = res_cur_page_array; }); _self.consoleLog("getCurPageArray", "cur_page_array", cur_page_array); callback(cur_page_array); }, main: function() { var _self = this; } } return getFunction; }; $scope.getPages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageBlog: function(page_name, blog_id, blog_name_url) { var _self = this; var page = page_name; page = (blog_id == '' || blog_name_url == '') ? page : page + "/" + blog_id + "-" + blog_name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.getCur = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getLeft: function() { var _self = this; var index = ($scope.data_api.load_more.cur_page - 1 != 0) ? $scope.data_api.load_more.cur_page - 1 : false; _self.consoleLog("getLeft", "index", index); if (index != false) { $scope.loadPage(index); } }, getRight: function() { var _self = this; var _self = this; var cur_pages = Math.round($scope.data_api.load_more.total_rows / $scope.data_api.load_more.per_page); var index = ($scope.data_api.load_more.cur_page + 1 < cur_pages) ? $scope.data_api.load_more.cur_page + 1 : false; _self.consoleLog("getRight", "index", index); if (index != false) { $scope.loadPage(index); } }, } return getFunction; }; /* get api */ $scope.data_api = { blog_id: false, load_more: { load: false, cur_page: 1, cur_page_array: [], per_page: 9, total_rows: 0 }, product: { data_send: {}, api: "product/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.loadPage = function(index) { $scope.data_api.product = { data_send: {}, api: "product/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } } $scope.data_api.load_more.cur_page = parseInt(index); $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.product.data_array_state = state; _self.getBlogId(params, function(res_blog_id) { _self.formatDataSend($scope.data_api.product, function(res_data) { var filter_json = { "referral_id_array": [$scope.referralid], } var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) } res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; _self.getCurPageArray($scope.data_api.load_more.cur_page, $scope.data_api.load_more.per_page, res_api.data.total_rows, function(res_cur_page_array) { $scope.data_api.load_more.cur_page_array = res_cur_page_array; }); }); }); }); }); }); }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.product.data_array_state = state; _self.getBlogId(params, function(res_blog_id) { _self.formatDataSend($scope.data_api.product, function(res_data) { var filter_json = { "referral_id_array": [$scope.referralid], } var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) } res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; _self.getCurPageArray($scope.data_api.load_more.cur_page, $scope.data_api.load_more.per_page, res_api.data.total_rows, function(res_cur_page_array) { $scope.data_api.load_more.cur_page_array = res_cur_page_array; }); }); }); }); }); }); /* get api */ }; return promise; });_ui_share_app.directive('componentCategoryFeaturedTypeA', function($rootScope, $routeParams, $location) { var templateName = 'componentCategoryFeaturedTypeA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var data = { consoleLog: function(name, data) { console.log(name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, locationUrl: function(url) { if (url != "") { $location.url(url).replace(); } }, windowLocation: function(url) { if (url != "") { window.location.href = url; } }, main: function() { var _self = this; } } return data; }; $scope.dataArray = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataSet = [{ api: "referral/lists", dataSend: { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 5, 'txt_sortby': 'referral_sort_index_asc_time_desc', 'txt_filter_json': JSON.stringify({ "badge_id_array": [16] }) }, }]; $scope.getData().dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { $scope.dataArrayState = $scope.getData().stateData(true, false); $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayState = $scope.getData().stateData(false, true); $scope.getData().consoleLog("getData : dataArray : ", $scope.dataArray); }); }); }; return promise; });_ui_share_app.directive('componentCategoryIdA', function($rootScope, $routeParams) { var templateName = 'componentCategoryIdA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referralid: '@referralid', size: '@size', sizelist: '@sizelist', sort: '@sort', col: '@col', component: '@component', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.size = (typeof $scope.size !== 'undefined') ? $scope.size : 8; $scope.sizelist = (typeof $scope.sizelist !== 'undefined') ? $scope.sizelist : 4; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(referralid) { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = { 'referral_id_array': [referralid] }; var dataSend = { 'cur_page': 1, 'per_page': $scope.sizelist, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.referralid); $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentCategoryListsA', function($rootScope, $routeParams, $location) { var templateName = 'componentCategoryListsA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { pagename: '@pagename', categorycol: '@categorycol', productcol: '@productcol', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.params_referral_id = $routeParams.referral_id; $scope.tab = ""; $scope.view = 'category'; $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.$watch('categorycol', function(newValue, oldValue) { if (!newValue) { return; } $scope._categorycol = newValue.toString().split(","); }); $scope.getCategoryCol = function(n) { return (typeof $scope._categorycol != 'undefined') ? (typeof $scope._categorycol[n] != 'undefined' && $scope._categorycol[n] != '') ? $scope._categorycol[n] : 12 : 12; }; $scope.$watch('productcol', function(newValue, oldValue) { if (!newValue) { return; } $scope._productcol = newValue.toString().split(","); }); $scope.getProductCol = function(n) { return (typeof $scope._productcol != 'undefined') ? (typeof $scope._productcol[n] != 'undefined' && $scope._productcol[n] != '') ? $scope._productcol[n] : 12 : 12; }; $scope._dataArrayLength = 0; $scope._dataArrayId = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArrayId = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {}; var dataSend = { 'txt_referral_id': id, 'txt_filter_json': JSON.stringify(filter_json) }; console.log("componentCategoryListsA _getDataArrayId dataSend : ", dataSend); GAEAPI.get('referral/id', dataSend, $scope).then(function(output) { if (output.ok === 1) { $scope._dataArrayId = output.data; console.log("componentCategoryListsA _getDataArrayId _dataArrayId : ", $scope._dataArrayId); $scope.tab = output.data.referral_name; console.log("componentCategoryListsA _getDataArrayId tab : ", $scope.tab); $scope._getDataArrayProduct(id); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope._dataArrayProduct = []; $scope._getDataArrayProduct = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "referral_id_array": [id], }; var dataSend = { 'cur_page': 1, 'per_page': 24, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; console.log("componentCategoryListsA _getDataArrayProduct dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok === 1) { $scope._dataArrayProduct = output.data.dataList; $scope._dataArrayLength = output.data.dataList.length; console.log("componentCategoryListsA _getDataArrayProduct _dataArrayProduct : ", $scope._dataArrayProduct); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope._dataArray = []; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; console.log("componentCategoryListsA _getDataArray dataSend : ", dataSend); GAEAPI.get('referral/map', dataSend, $scope).then(function(output) { if (output.ok === 1) { $scope._dataArray = output.data; $scope._dataArrayLength = output.data.length; console.log("componentCategoryListsA _getDataArray _dataArray : ", $scope._dataArray); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } // $scope.intab = function(id, data) { // $scope.tab = data; // console.log('intab : ', id, data); // $scope._getDataArrayId(id); // }; $scope.$watch('params_referral_id', function(newValue, oldValue) { console.log("params_referral_id : ", newValue, oldValue); if (newValue != undefined) { $scope._getDataArray(); $scope._getDataArrayId(newValue); $scope.view = 'product'; } else { $scope._getDataArray(); $scope.view = 'category'; } }); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentCategoryListsIdA', function($rootScope, $routeParams) { var templateName = 'componentCategoryListsIdA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', refid: '@refid', _font: '@font', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); if (typeof $scope.refid !== 'undefined') { var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': id, }; } else { var dataSend = { 'txt_referral_type_id': 11, }; } GAEAPI.get('referral/map', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.refid); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentCategoryListsProductA', function($rootScope, $routeParams, $location) { var templateName = 'componentCategoryListsProductA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', referralid: '@referralid', productcol: '@productcol', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.$watch('productcol', function(newValue, oldValue) { if (!newValue) { return; } $scope._productcol = newValue.toString().split(","); }); $scope.getProductCol = function(n) { return (typeof $scope._productcol != 'undefined') ? (typeof $scope._productcol[n] != 'undefined' && $scope._productcol[n] != '') ? $scope._productcol[n] : 12 : 12; }; $scope._dataArrayProduct = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArrayProduct = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "referral_id_array": [id], }; var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; console.log("componentCategoryListsA _getDataArrayProduct dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok === 1) { $scope._dataArrayProduct = output.data.dataList; console.log("componentCategoryListsA _getDataArrayProduct _dataArrayProduct : ", $scope._dataArrayProduct); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.$watch('referralid', function(newValue, oldValue) { console.log("referralid : ", newValue, oldValue); if (newValue != undefined) { $scope._getDataArrayProduct(newValue); } }); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentCategoryMapA', function($rootScope, $routeParams) { var templateName = 'componentCategoryMapA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', refid: '@refid', _font: '@font', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._dataArray = []; $scope._dataArrayDone = false; $scope._getDataArray = function() { if (typeof $scope.refid !== 'undefined') { var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': $scope.refid, }; } else { var dataSend = { 'txt_referral_type_id': 11, }; } GAEAPI.get('referral/map', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope._dataArrayDone = true; console.log("_dataArray", $scope._dataArray); } }); }; $scope._getDataArray(); $scope.viewDataWidth = function() { return $(window).width(); }; $scope.viewDataHeight = function() { return $(window).height(); }; $scope._arrayControlView = []; $scope._controlView = null; $scope.controlView = function() { if ($(window).width() >= 1200) { $scope._controlView = 4; $scope._arrayControlView[0] = 0; for (var i = 1; i <= 10; i++) { $scope._arrayControlView[i] = $scope._arrayControlView[i - 1] + 4; } } else if ($(window).width() >= 992) { $scope._controlView = 4; $scope._arrayControlView[0] = 0; for (var i = 1; i <= 10; i++) { $scope._arrayControlView[i] = $scope._arrayControlView[i - 1] + 4; } } else if ($(window).width() >= 768) { $scope._controlView = 3; $scope._arrayControlView[0] = 0; for (var i = 1; i <= 10; i++) { $scope._arrayControlView[i] = $scope._arrayControlView[i - 1] + 3; } } else if ($(window).width() < 768) { $scope._controlView = 3; $scope._arrayControlView[0] = 0; for (var i = 1; i <= 10; i++) { $scope._arrayControlView[i] = $scope._arrayControlView[i - 1] + 3; } } return $scope._controlView; }; $scope.controlView(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debugcategory !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentCategoryMenuDropdownA', function($rootScope, $routeParams) { var templateName = 'componentCategoryMenuDropdownA'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { _font: '@font', imgpath: '@imgpath', _menustart: '@menustart', refid: '@refid', _color: '@color', _backgroundcolor: '@backgroundcolor', _backgroundcolordropdown: '@backgroundcolordropdown', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.activeMenu = function() { /*document.getElementById("activeMenu").classList.toggle("show"); $('body').css('position','fixed');*/ if (!angular.element('._headings').hasClass('active')) { angular.element('._headings').addClass('active') } else { angular.element('._headings').removeClass('active') } }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._heading = ''; if (typeof $scope._viewRouteParams().referral_name !== 'undefined' && typeof $scope._viewRouteParams().referral_name != '') { $scope._heading = $scope._viewRouteParams().referral_name; } else { $scope._heading = $scope._menustart; } $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.myFunctionDropdown = function(len) { if (len > 0) { if ($scope._viewRouteParams().referral_name != 'สั่งอาหาร') { $scope.activeMenu(); document.getElementById("myDropdown").classList.toggle("show"); } } } $scope.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } $scope._category_id = false; $scope._get_category_id = function() { if (typeof $scope.refid !== 'undefined') { var dataSend = { 'txt_referral_id': $scope.refid, }; } GAEAPI.get('referral/id', dataSend, $scope).then(function(res) { if (res.ok === 1) { $scope._category_id = res.data; /*$scope._heading = $scope._category_id.referral_name;*/ } }); }; $scope._get_category_id(); $scope._page_lists = false; $scope._page_lists_load = false; $scope._get_page_lists = function() { $scope._clear_page_lists(); var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'page_lastest_create' }; GAEAPI.get('page/lists', dataSend, $scope).then(function(res) { $scope._page_lists_load = true; if (res.ok === 1) { $scope._page_lists = res.data.dataList; angular.forEach($scope._page_lists, function(item, key) { if (item.page_search_url == "") { item.page_search_url = item.page_id; } }); } }); }; $scope._clear_page_lists = function() { $scope._page_lists = false; $scope._page_lists_load = false; }; $scope._get_page_lists(); $scope._page_category = false; $scope._page_category_load = false; $scope._get_page_category = function() { $scope._clear_page_lists(); if (typeof $scope.refid !== 'undefined') { var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': $scope.refid, }; } else { var dataSend = { 'txt_referral_type_id': 11, }; } GAEAPI.get('referral/map', dataSend, $scope).then(function(res) { $scope._page_category_load = true; if (res.ok === 1) { $scope._page_category = res.data; } }); }; $scope._clear_page_category = function() { $scope._page_category = false; $scope._page_category_load = false; }; $scope._get_page_category(); $scope.displayImage = function(image_url, prefix) { var urlreturn = GAEAPI.getGaeImageUrl(image_url, prefix); return urlreturn; } $scope.viewDataWidth = function() { return $(window).width(); }; $scope.viewDataHeight = function() { return $(window).height(); }; $scope._testspeed = null; $scope._arrayControlView = []; $scope._controlView = null; $scope.controlView = function() { if ($(window).width() >= 1200) { $scope._controlView = 4; $scope._arrayControlView[0] = 0; for (var i = 1; i <= 10; i++) { $scope._arrayControlView[i] = $scope._arrayControlView[i - 1] + 4; } } else if ($(window).width() >= 992) { $scope._controlView = 4; $scope._arrayControlView[0] = 0; for (var i = 1; i <= 10; i++) { $scope._arrayControlView[i] = $scope._arrayControlView[i - 1] + 4; } } else if ($(window).width() >= 768) { $scope._controlView = 3; $scope._arrayControlView[0] = 0; for (var i = 1; i <= 5; i++) { $scope._arrayControlView[i] = $scope._arrayControlView[i - 1] + 3; } } else if ($(window).width() < 768) { $scope._controlView = 3; $scope._arrayControlView[0] = 0; for (var i = 1; i <= 10; i++) { $scope._arrayControlView[i] = $scope._arrayControlView[i - 1] + 3; } } return $scope._controlView; }; $scope.controlView(); $scope.showDebug = function() { return (typeof $routeParams.debugcategorymenu !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentCategorySilde', function($rootScope, $routeParams) { var templateName = 'componentCategorySilde'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', refid:'@refid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarouselData = function(elem) { console.debug('mkCarouselData: trigger'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 10, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1330, settings: { slidesToShow: 10, } }, { breakpoint: 991, settings: { slidesToShow: 8, } }, { breakpoint: 767, settings: { slidesToShow: 6, } }, { breakpoint: 692, settings: { slidesToShow: 4, } },{ breakpoint: 540, settings: { slidesToShow: 2, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._dataArray = []; $scope._dataArrayDone = false; $scope._getDataArray = function() { if(typeof $scope.refid !== 'undefined'){ var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': $scope.refid, }; }else{ var dataSend = { 'txt_referral_type_id': 11, }; } GAEAPI.get('referral/map', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; console.log("_dataArray",$scope._dataArray); } }); }; $scope._getDataArray(); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.displayImage = function(image_url, prefix) {return GAEAPI.getGaeImageUrl(image_url, prefix);} }; return promise; });_ui_share_app.directive('componentCategoryTable', function($rootScope, $routeParams) { var templateName = 'componentCategoryTable'; var componentMain = 'componentCategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('componentCategoryTable : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(array, api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(array, api, dataSend); }, getApi: function(array, api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(array, output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 300, total_rows: 0 }; $scope.dataMapArray = []; $scope.dataMapArrayState = $scope.getData().stateData(false, false); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); /* category */ /* $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; var dataSend = { 'txt_referral_type_id': 11, 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend(0, 'referral/lists', dataSend, function(array, api, dataSend) { $scope.getData().getApi(array, api, dataSend, function(array, output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); for (var i = 0; i < output.data.dataList.length; i++) { var txt_filter_json = {}; var dataSend = { 'txt_referral_id': output.data.dataList[i].referral_id }; $scope.getData().dataSend(i, 'referral/relation', dataSend, function(array, api, dataSend) { $scope.getData().getApi(array, api, dataSend, function(array, output) { $scope.dataMapArray[array] = output.data; }); }); } }); }); }); */ /* category */ /* product */ $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend(0, 'product/lists', dataSend, function(array, api, dataSend) { $scope.getData().getApi(array, api, dataSend, function(array, output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); /* product */ $scope.loadMore = function() { var getFunction = { consoleLog: function(name, data) { console.log('componentCategoryTable : ', name, data); }, stateData: function(state) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", state); _self.consoleLog("getData : ", "------- stateData -------"); return state; }, main: function() { var _self = this; } } return getFunction; }; /* category */ /* $scope.load = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = $scope.loadMore().stateData(true); $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; var dataSend = { 'txt_referral_type_id': 11, 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend(0, 'referral/lists', dataSend, function(array, api, dataSend) { $scope.getData().getApi(array, api, dataSend, function(array, output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; for (var i = 0; i < output.data.dataList.length; i++) { var txt_filter_json = {}; var dataSend = { 'txt_referral_id': output.data.dataList[i].referral_id }; var int_array = ($scope.dataArrayPageState.per_page * ($scope.dataArrayPageState.cur_page - 1)) + i; $scope.getData().dataSend(int_array, 'referral/relation', dataSend, function(array, api, dataSend) { $scope.getData().getApi(array, api, dataSend, function(array, output) { $scope.dataMapArray[array] = output.data; }); }); } } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = $scope.loadMore().stateData(false); $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); } }; */ /* category */ /* product */ $scope.load = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = $scope.loadMore().stateData(true); $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend(0, 'product/lists', dataSend, function(array, api, dataSend) { $scope.getData().getApi(array, api, dataSend, function(array, output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = $scope.loadMore().stateData(false); $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); } }; /* product */ /* download */ $scope.imageDownload = function(url, fileName) { var xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = "blob"; xhr.onload = function() { var urlCreator = window.URL || window.webkitURL; var imageUrl = urlCreator.createObjectURL(this.response); var tag = document.createElement('a'); tag.href = imageUrl; tag.download = fileName; document.body.appendChild(tag); tag.click(); document.body.removeChild(tag); } xhr.send(); }; /* download */ }; return promise; });_ui_share_app.directive('componentCategoryCustomslideA', function($rootScope, $routeParams) { var componentMain = 'componentCategory'; var componentChild = 'customslideA'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', dataItem: '=data', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; /*$scope.test_json = JSON.stringify($scope.data); $scope.dataItem = JSON.parse($scope.test_json);*/ $scope.slideProductDeal = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 3000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; });_ui_share_app.directive('componentCategoryCustomslideB', function($rootScope, $routeParams) { var componentMain = 'componentCategory'; var componentChild = 'customslideB'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', dataItem: '=data', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; /*$scope.test_json = JSON.stringify($scope.data); $scope.dataItem = JSON.parse($scope.test_json);*/ $scope.slideProductDeal = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 3000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 2, } }, { breakpoint: 768, settings: { slidesToShow: 2, } }, { breakpoint: 480, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; }); _ui_share_app.directive('componentCategoryCardA', function ($rootScope, $routeParams) { var templateName = 'componentCategoryCardA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', stylebutton :'@stylebutton', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.ref_id = $routeParams.referral_id; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.FetchDisplayCategory = function (ref_id) { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; if(typeof ref_id !== 'undefined'){ d.txt_parent_id = ref_id; } GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } console.log("referral display", d, e.data, ref_id); }); }; /*if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); }*/ /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('ref_id', function (newValue, oldValue) { if (!newValue || newValue == 0){ return $scope.FetchDisplayCategory(); } $scope.FetchDisplayCategory(newValue); }); /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Check if child array exist */ $scope.checkChild = function(object){ return (!object.referral_sub_array.length) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentCategoryGridA', function ($rootScope, $routeParams) { var templateName = 'componentCategoryGridA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { primary:'@primary', color:'@color', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ var jsonFilter = JSON.stringify({'type_number':$scope.type}); var d = { 'txt_referral_type_id': 11 }; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok === 1){ $scope.dataArray = e.data; } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentCategoryGridC', function ($rootScope, $routeParams) { var templateName = 'componentCategoryGridC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { primary:'@primary', color:'@color', name:'@name', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ var jsonFilter = JSON.stringify({'type_number':$scope.type}); var d = { 'txt_referral_type_id': 11 }; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok === 1){ $scope.dataArray = e.data; } }); }; $scope.getData(); $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentCategoryGridCa', function ($rootScope, $routeParams) { var componentMain = 'componentCategoryGridC'; var componentChild = 'a'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild+ '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { primary:'@primary', color:'@color', name:'@name', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ var jsonFilter = JSON.stringify({'type_number':$scope.type}); var d = { 'txt_referral_type_id': 11 }; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok === 1){ $scope.dataArray = e.data; } }); }; $scope.getData(); $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentCategoryGridF', function ($rootScope, $routeParams) { var templateName = 'componentCategoryGridF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', primary:'@primary', color:'@color', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ var d = { 'txt_referral_type_id': 11, 'cur_page':1, 'per_page' : 2, 'txt_sortby' : 'referral_oldest_create' }; GAEAPI.get('referral/lists',d,$scope).then(function(e){ if(e.ok === 1){ $scope.dataArray = e.data.dataList; } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentCategoryGridG', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCategoryGridG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'auto':'@auto', 'feature':'@feature', 'referralid':'@referralid', 'imgpath':'@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval) { $scope.use_auto = (typeof $scope.auto !== 'undefined' && $scope.auto == 'true') ? true : false; $scope.use_feature = (typeof $scope.feature !== 'undefined' && $scope.feature == 'true') ? true : false; /** * Check if object array available for "website application" or "Mobile application" or "Featured" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope._showFeature = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 16) { r = true; break; } } return r; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; $scope.data = []; $scope.data_done = false; /* Get referral data (all) * @params none * @return array */ $scope.getData = function(){ $scope.data = []; $scope.data_done = false; var filterJson = {'badge_id_array':[18]}; if($scope.use_feature){ filterJson.badge_id_array.push(16); } var d = { 'txt_referral_type_id':11, }; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok == 1){ console.log("3a : before", e.data); if($scope.use_feature){ var dummy = []; angular.forEach(e.data, function(item,key){ if($scope._showFeature(item.referral_badge)){ dummy.push(item); } }); $scope.data = dummy; $scope.data_done = true; $scope.buildImageSlider($scope.data); console.log("3a : dummy", dummy); console.log("3a", $scope.data); } else{ $scope.data = e.data; $scope.data_done = true; $scope.buildImageSlider($scope.data); console.log("3a", $scope.data); } } }); }; /* Get referral data (by referral_id) * @params id = referral_id * @return array */ $scope.getDataReferral = function(id){ $scope.data = []; $scope.data_done = false; var d = { 'txt_referral_id':id }; GAEAPI.get('referral/id_map',d,$scope).then(function(e){ if(e.ok == 1){ $scope.data[0] = e.data; $scope.data_done = true; $scope.buildImageSlider($scope.data); } }); }; /* * params listener * @params newValue * @params oldValue * @return function */ $scope.$watch('auto', function (newValue, oldValue) { if (!newValue){ if(typeof $scope.referralid !== 'undefined' && $scope.referralid !== ''){ return $scope.getDataReferral($scope.referralid); } else { return $scope.getData(); } } $scope.getData(); }); /* * check if image array exist or build dummy image array * @params arrayObject = object array * @return array */ $scope.buildImageSlider = function(){ var imageArray = function(idx){ if(idx == 0){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1.jpg'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'}, ]; } else if(idx == 1){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_2.png'}, ]; } else { return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'}, ]; } }; var imageBannerArray = function(idx){ if(idx == 0){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1.jpg'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2.jpg'}, ]; } else if(idx == 1) { return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1_2.png'}, ]; } else { return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2_2.png'}, ]; } }; angular.forEach($scope.data, function(item, key){ if(!item.referral_image.length){ item.referral_image = imageArray(key); } item.referral_image_banner = imageBannerArray(key); }); }; /* Make Carousel */ $scope._makeProductToCarousel = function (keyCustom) { var elementName = '[data-id="' + keyCustom + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, "", keyCustom); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(){ return "-" + (($('.row.slick-slider[data-id="'+$scope._uniqueKey+'"]').height() / 2) + 34) + "px"; }; /* Carousel Arrow Click */ $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; /* Carousel Arrow Click */ $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { if($('[data-id*="gallery-"]').length){ $('[data-id*="gallery-"]').not('.slick-initialized').each(function(Key,Object){ if($(this).find('.imageItem').length > 0){ $scope._makeProductToCarousel($(this).attr('data-id')); } }); } }); /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; }); _ui_share_app.directive('componentCategoryGridH', function ($rootScope, $routeParams, sliderProvider, $location) { var templateName = 'componentCategoryGridH'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'auto':'@auto', 'feature':'@feature', 'referralid':'@referralid', 'imgpath':'@imgpath', 'margin':'@margin', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.use_auto = (typeof $scope.auto !== 'undefined' && $scope.auto == 'true') ? true : false; $scope.use_feature = (typeof $scope.feature !== 'undefined' && $scope.feature == 'true') ? true : false; /** * Check if object array available for "website application" or "Mobile application" or "Featured" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope._showFeature = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 16) { r = true; break; } } return r; }; /* --------- START : 1 ------------*/ /* Extract sub referral id from parent */ $scope._mergeSubReferral = function(originalArray, r){ if(!r.referral_sub_array.length){ return originalArray; } var a = []; angular.forEach(r.referral_sub_array, function(i, k) { if($scope._showFeature(i.referral_badge)){ a.push(parseInt(i.referral_id)); $scope.dummyFeatureName.push(i); if(i.referral_image.length){ $scope.dummyReferralImage.push(i.referral_image[0]); } } if(i.referral_sub_array.length > 0){ angular.forEach(i.referral_sub_array, function(ii,kk){ if($scope._showFeature(ii.referral_badge)){ a.push(parseInt(ii.referral_id)); $scope.dummyFeatureName.push(ii); if(ii.referral_image.length){ $scope.dummyReferralImage.push(ii.referral_image[0]); } } if(ii.referral_sub_array.length > 0){ angular.forEach(ii.referral_sub_array, function(iii,kkk){ if($scope._showFeature(iii.referral_badge)){ a.push(parseInt(iii.referral_id)); $scope.dummyFeatureName.push(iii); if(iii.referral_image.length){ $scope.dummyReferralImage.push(iii.referral_image[0]); } } if(iii.referral_sub_array.length > 0){ angular.forEach(iii.referral_sub_array, function(iiii,kkk){ if($scope._showFeature(iiii.referral_badge)){ a.push(parseInt(iiii.referral_id)); $scope.dummyFeatureName.push(iiii); if(iiii.referral_image.length){ $scope.dummyReferralImage.push(iiii.referral_image[0]); } } }); } }); } }); } }); return (a.length) ? a.concat(originalArray) : originalArray; }; /* --------- END : 1 ------------*/ /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; $scope.data = []; $scope.data_done = false; $scope.dummyFeatureName = []; $scope.dummyReferralImage = []; /* Get referral data (all) * @params none * @return array */ /* $scope.getData = function(){ $scope.data = []; $scope.data_done = false; $scope.dummyFeatureName = []; var filterJson = {'badge_id_array':[18]}; var d = { 'txt_referral_type_id':11, }; var dummy = []; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok == 1){ console.log("3a : before", e.data); if($scope.use_feature){ var dummyReferral = []; dummy = []; angular.forEach(e.data, function(item, key){ item.referral_product_array = []; if($scope._showFeature(item.referral_badge)){ dummyReferral.push(item); dummy.push(parseInt(item.referral_id)); if(item.referral_sub_array.length){ dummy = $scope._mergeSubReferral(dummy, item); } } }); $scope.data = dummyReferral; $scope.data_done = true; $scope.buildImageSlider($scope.data); } else{ dummy = []; angular.forEach(e.data, function(item, key){ dummy.push(parseInt(item.referral_id)); if(item.referral_sub_array.length){ dummy = $scope._mergeSubReferral(dummy, item); } }); $scope.data = e.data; $scope.data_done = true; $scope.buildImageSlider($scope.data); } } if(dummy.length){ $scope.getDataProductByReferralArray(dummy); } }); }; */ var referralDisplayClass = function(){ var object = { getOnlyBadgeIdArray(badgeArray){ var result = []; for(var index in badgeArray){ var badgeData = badgeArray[index]; var badge_id = GAEAPI.getValue(badgeData["badge_id"],""); if(badge_id!=""){ result.push(badge_id); } } return result; }, getOnlyReferralIdArray(referralArray){ var result = []; for(var index in referralArray){ var referralData = referralArray[index]; var referral_id = GAEAPI.getValue(referralData["referral_id"],""); if(referral_id!=""){ result.push(referral_id); } } return result; }, getAllSubReferral(referralArray,resultArray){ var self = this; for(var index in referralArray){ var referralData = referralArray[index]; var badgeIdArray = self.getOnlyBadgeIdArray(referralData.referral_badge); if(badgeIdArray.indexOf("16")>=0){ resultArray.push(referralData); } var subReferralArray = GAEAPI.getValue(referralData["referral_sub_array"],[]); if(subReferralArray.length>0){ self.getAllSubReferral(subReferralArray,resultArray); } } }, getImageDataArray(referralArray,imageArray){ for(var index in referralArray){ var referralData = referralArray[index]; var referralImageArray = GAEAPI.getValue(referralData["referral_banner_array"],[]); if(referralImageArray.length>0){ imageArray.push(referralImageArray[0]); } } }, getImageBannerDataArray(referralArray,imageArray){ for(var index in referralArray){ var referralData = referralArray[index]; var referralBannerArray = GAEAPI.getValue(referralData["referral_image"],[]); if(referralBannerArray.length>0){ for(indexTwo in referralBannerArray){ if(referralBannerArray[indexTwo]["banner_is_enable"] != 0){ imageArray.push(referralBannerArray[indexTwo]); } } } } }, generateCategoryDisplay(index,referralArray,callback){ var self = this; if(referralArray.length<=index){ if(callback){callback();} return false; } var referralData = referralArray[index]; var referral_id = GAEAPI.getValue(referralData["referral_id"],""); var subReferralIdArray = []; console.log("subReferralIdArray : start 1",subReferralIdArray); console.log("subReferralIdArray : start 1",referralData); self.getAllSubReferral(referralData.referral_sub_array,subReferralIdArray); console.log("subReferralIdArray : function 2 getAllSubReferral",subReferralIdArray); console.log("subReferralIdArray : function 2 getAllSubReferral",referralData); referralData["referral_sub_array_two_d"] = referralData.referral_sub_array; referralData["referral_feature_name"] = subReferralIdArray; var resultIdArray = self.getOnlyReferralIdArray(subReferralIdArray); resultIdArray.push(referral_id); referralData["id_array"] = resultIdArray; console.log("data_product_array_55 : ",resultIdArray); var dataSend = { 'cur_page': 1, 'per_page': 8, 'txt_filter_json':JSON.stringify({'badge_id_array':[18,16],'referral_id_array_or':resultIdArray}) }; console.log("product/lists : generateCategoryDisplay : dataSend ",dataSend); GAEAPI.get("product/lists",dataSend,$scope).then(function(res){ console.log("product/lists : generateCategoryDisplay : res : ",res); var productArray = []; if(res.ok==1){ productArray = res.data.dataList; } referralData["referral_product_array"] = productArray; }); console.log("generateCategoryDisplay : index : "+index+" : ",referralData); self.generateCategoryDisplay((index+1),referralArray,callback); var badgeIdArray = self.getOnlyBadgeIdArray(referralData.referral_badge); if(badgeIdArray.indexOf("16")>=0){ $scope.data.push(referralData); console.log("data_array_first_top",$scope.data); var imageArray = GAEAPI.getValue(referralData["referral_image"],[]); self.getImageDataArray(subReferralIdArray,imageArray); referralData["referral_image_all_array"] = imageArray; } } }; return object; } var referralDisplay = referralDisplayClass(); var mapDataArray = []; $scope.getData = function(){ $scope.data = []; $scope.data_done = false; $scope.dummyFeatureName = []; var filterJson = {'badge_id_array':[18]}; var dataSend = { 'txt_referral_type_id':11, 'txt_sortby' : "referral_sort_index_desc_name_asc", }; var dummy = []; console.log('referral/map : dataSend : ',dataSend); GAEAPI.get('referral/map',dataSend,$scope).then(function(res){ console.log('referral/map : res : ',res); if(res.ok==1){ mapDataArray = res.data; referralDisplay.generateCategoryDisplay(0,mapDataArray,function(){ $scope.data_done = true; }); } }); }; $scope.data_product = []; $scope.data_product_done = false; /* Get product list by referral array * @params {objectArray} referral array * @return array */ $scope.getDataProductByReferralArray = function(objectArray){ var d = { 'cur_page': 1, 'per_page': 8, 'txt_filter_json':JSON.stringify({'badge_id_array':[18,16],'referral_id_array_in':objectArray}) }; var dummy = []; $scope.data_product_done = false; GAEAPI.get('product/lists',d,$scope).then(function(e){ if(e.ok === 1){ $scope.data_product = e.data.dataList; $scope.data_product_done = true; angular.forEach($scope.data, function(item,key){ item.referral_feature_name = $scope.dummyFeatureName; item.referral_product_array = e.data.dataList; item.referral_image_all_array = $scope.dummyReferralImage; }); console.log("getDataProductByReferralArray: referral data",$scope.data); console.log("getDataProductByReferralArray: referral_id_array_in",objectArray); console.log("getDataProductByReferralArray: params",d); console.log("getDataProductByReferralArray: data",e); } }); }; /* Get referral data (by referral_id) * @params id = referral_id * @return array */ $scope.getDataReferral = function(id){ $scope.data = []; $scope.data_done = false; var d = { 'txt_referral_id':id }; GAEAPI.get('referral/id_map',d,$scope).then(function(e){ if(e.ok == 1){ $scope.data[0] = e.data; $scope.data_done = true; $scope.buildImageSlider($scope.data); console.log("data_array_first",e.data); } }); }; /* * params listener * @params newValue * @params oldValue * @return function */ $scope.$watch('use_auto', function (newValue, oldValue) { if (!newValue && typeof $scope.referralid !== 'undefined' && $scope.referralid !== ''){ return $scope.getDataReferral($scope.referralid); } $scope.getData(); }); /* * check if image array exist or build dummy image array * @params arrayObject = object array * @return array */ $scope.dummyArrayImageGallery = [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_2.png'}, ]; $scope.buildImageSlider = function(){ var imageArray = function(idx){ if(idx == 0){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1.jpg'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'}, ]; } else if(idx == 1){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_2.png'}, ]; } else { return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'}, ]; } }; var imageBannerArray = function(idx){ if(idx == 0){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1.jpg'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2.jpg'}, ]; } else if(idx == 1) { return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1_2.png'}, ]; } else { return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2_2.png'}, ]; } }; angular.forEach($scope.data, function(item, key){ if(!item.referral_image.length){ item.referral_image = imageArray(key); } item.referral_image_banner = imageBannerArray(key); }); }; /* Make Carousel */ $scope._makeProductToCarousel = function (keyCustom, type) { var elementName = '[data-id="' + keyCustom + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, "", keyCustom); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(){ return "-" + (($('.row.slick-slider[data-id="'+$scope._uniqueKey+'"]').height() / 2) + 34) + "px"; }; /* Carousel Arrow Click */ $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; /* Carousel Arrow Click */ $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { $timeout(function(){ if($('.gallery-block[data-id]').length){ $('.gallery-block[data-id]').not('.slick-initialized').each(function(Key,Object){ if($(this).find('.imageItem').length > 0){ $scope._makeProductToCarousel($(this).attr('data-id'), 'gallery'); } }); } },500); }); /*angular.element($window).bind('load', function(){*/ if($location.path() == '/' || $location.path() == '/home'){ var checkSliderImageProduct = setInterval(function(){ console.log("checking...", $('.cart-block').not('.slick-initialized').length); if($('.cart-block.slick-initialized').length == $('.cart-block').length && $scope.data_product.length > 0){ clearInterval(checkSliderImageProduct); return; } else { $('.cart-block').not('.slick-initialized').each(function(){ if($(this).find('.row-product').length){ var elementName = '[data-id="' + $(this).data('id') + '"]'; var paramsOptions = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; sliderProvider(elementName, paramsOptions, "", $(this).data('id')); } }); } },1000); } /*});*/ $scope.displayImage = function(image_url, prefix) {return GAEAPI.getGaeImageUrl(image_url, prefix);} /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Open Link in other windows */ $scope.openWindows = function(stringUrl){ return window.open(stringUrl, '_blank', 'location=yes,height='+$(window).height()+',width='+$(window).width()+',scrollbars=yes,status=yes'); }; }; return promise; }); _ui_share_app.directive('componentCategoryGridI', function ($rootScope, $routeParams, sliderProvider, $location) { var templateName = 'componentCategoryGridI'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'auto':'@auto', 'feature':'@feature', 'referralid':'@referralid', 'imgpath':'@imgpath', 'margin':'@margin', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.use_auto = (typeof $scope.auto !== 'undefined' && $scope.auto == 'true') ? true : false; $scope.use_feature = (typeof $scope.feature !== 'undefined' && $scope.feature == 'true') ? true : false; /** * Check if object array available for "website application" or "Mobile application" or "Featured" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope._showFeature = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 16) { r = true; break; } } return r; }; /* --------- START : 1 ------------*/ /* Extract sub referral id from parent */ $scope._mergeSubReferral = function(originalArray, r){ if(!r.referral_sub_array.length){ return originalArray; } var a = []; angular.forEach(r.referral_sub_array, function(i, k) { if($scope._showFeature(i.referral_badge)){ a.push(parseInt(i.referral_id)); $scope.dummyFeatureName.push(i); if(i.referral_image.length){ $scope.dummyReferralImage.push(i.referral_image[0]); } } if(i.referral_sub_array.length > 0){ angular.forEach(i.referral_sub_array, function(ii,kk){ if($scope._showFeature(ii.referral_badge)){ a.push(parseInt(ii.referral_id)); $scope.dummyFeatureName.push(ii); if(ii.referral_image.length){ $scope.dummyReferralImage.push(ii.referral_image[0]); } } if(ii.referral_sub_array.length > 0){ angular.forEach(ii.referral_sub_array, function(iii,kkk){ if($scope._showFeature(iii.referral_badge)){ a.push(parseInt(iii.referral_id)); $scope.dummyFeatureName.push(iii); if(iii.referral_image.length){ $scope.dummyReferralImage.push(iii.referral_image[0]); } } if(iii.referral_sub_array.length > 0){ angular.forEach(iii.referral_sub_array, function(iiii,kkk){ if($scope._showFeature(iiii.referral_badge)){ a.push(parseInt(iiii.referral_id)); $scope.dummyFeatureName.push(iiii); if(iiii.referral_image.length){ $scope.dummyReferralImage.push(iiii.referral_image[0]); } } }); } }); } }); } }); return (a.length) ? a.concat(originalArray) : originalArray; }; /* --------- END : 1 ------------*/ /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; $scope.data = []; $scope.data_done = false; $scope.dummyFeatureName = []; $scope.dummyReferralImage = []; /* Get referral data (all) * @params none * @return array */ /* $scope.getData = function(){ $scope.data = []; $scope.data_done = false; $scope.dummyFeatureName = []; var filterJson = {'badge_id_array':[18]}; var d = { 'txt_referral_type_id':11, }; var dummy = []; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok == 1){ console.log("3a : before", e.data); if($scope.use_feature){ var dummyReferral = []; dummy = []; angular.forEach(e.data, function(item, key){ item.referral_product_array = []; if($scope._showFeature(item.referral_badge)){ dummyReferral.push(item); dummy.push(parseInt(item.referral_id)); if(item.referral_sub_array.length){ dummy = $scope._mergeSubReferral(dummy, item); } } }); $scope.data = dummyReferral; $scope.data_done = true; $scope.buildImageSlider($scope.data); } else{ dummy = []; angular.forEach(e.data, function(item, key){ dummy.push(parseInt(item.referral_id)); if(item.referral_sub_array.length){ dummy = $scope._mergeSubReferral(dummy, item); } }); $scope.data = e.data; $scope.data_done = true; $scope.buildImageSlider($scope.data); } } if(dummy.length){ $scope.getDataProductByReferralArray(dummy); } }); }; */ var referralDisplayClass = function(){ var object = { getOnlyBadgeIdArray(badgeArray){ var result = []; for(var index in badgeArray){ var badgeData = badgeArray[index]; var badge_id = GAEAPI.getValue(badgeData["badge_id"],""); if(badge_id!=""){ result.push(badge_id); } } return result; }, getOnlyReferralIdArray(referralArray){ var result = []; for(var index in referralArray){ var referralData = referralArray[index]; var referral_id = GAEAPI.getValue(referralData["referral_id"],""); if(referral_id!=""){ result.push(referral_id); } } return result; }, getAllSubReferral(referralArray,resultArray){ var self = this; for(var index in referralArray){ var referralData = referralArray[index]; var badgeIdArray = self.getOnlyBadgeIdArray(referralData.referral_badge); if(badgeIdArray.indexOf("16")>=0){ resultArray.push(referralData); } var subReferralArray = GAEAPI.getValue(referralData["referral_sub_array"],[]); if(subReferralArray.length>0){ self.getAllSubReferral(subReferralArray,resultArray); } } }, getImageDataArray(referralArray,imageArray){ for(var index in referralArray){ var referralData = referralArray[index]; var referralImageArray = GAEAPI.getValue(referralData["referral_banner_array"],[]); if(referralImageArray.length>0){ imageArray.push(referralImageArray[0]); } } }, getImageBannerDataArray(referralArray,imageArray){ for(var index in referralArray){ var referralData = referralArray[index]; var referralBannerArray = GAEAPI.getValue(referralData["referral_image"],[]); if(referralBannerArray.length>0){ for(indexTwo in referralBannerArray){ if(referralBannerArray[indexTwo]["banner_is_enable"] != 0){ imageArray.push(referralBannerArray[indexTwo]); } } } } }, generateCategoryDisplay(index,referralArray,callback){ var self = this; if(referralArray.length<=index){ if(callback){callback();} return false; } var referralData = referralArray[index]; var referral_id = GAEAPI.getValue(referralData["referral_id"],""); var subReferralIdArray = []; self.getAllSubReferral(referralData.referral_sub_array,subReferralIdArray); referralData["referral_feature_name"] = subReferralIdArray; var resultIdArray = self.getOnlyReferralIdArray(subReferralIdArray); resultIdArray.push(referral_id); referralData["id_array"] = resultIdArray; var dataSend = { 'cur_page': 1, 'per_page': 8, 'txt_json_filter':JSON.stringify({'badge_id_array':[18,16],'referral_id_array_in':resultIdArray}) }; console.log("product/lists : dataSend : ",dataSend); GAEAPI.get("product/lists",dataSend,$scope).then(function(res){ console.log("product/lists : res : ",res); var productArray = []; if(res.ok==1){ productArray = res.data.dataList; } referralData["referral_product_array"] = productArray; console.log("product/lists : referralData : ",referralData); }); console.log("generateCategoryDisplay : index : "+index+" : ",referralData); self.generateCategoryDisplay((index+1),referralArray,callback); var badgeIdArray = self.getOnlyBadgeIdArray(referralData.referral_badge); if(badgeIdArray.indexOf("16")>=0){ $scope.data.push(referralData); var imageArray = GAEAPI.getValue(referralData["referral_image"],[]); self.getImageDataArray(subReferralIdArray,imageArray); referralData["referral_image_all_array"] = imageArray; } } }; return object; } var referralDisplay = referralDisplayClass(); var mapDataArray = []; $scope.getData = function(){ $scope.data = []; $scope.data_done = false; $scope.dummyFeatureName = []; var filterJson = {'badge_id_array':[18]}; var dataSend = { 'txt_referral_type_id':11, }; var dummy = []; console.log('referral/map : dataSend : ',dataSend); GAEAPI.get('referral/map',dataSend,$scope).then(function(res){ console.log('referral/map : res : ',res); if(res.ok==1){ mapDataArray = res.data; referralDisplay.generateCategoryDisplay(0,mapDataArray,function(){ $scope.data_done = true; }); } }); }; $scope.data_product = []; $scope.data_product_done = false; /* Get product list by referral array * @params {objectArray} referral array * @return array */ $scope.getDataProductByReferralArray = function(objectArray){ var d = { 'cur_page': 1, 'per_page': 8, 'txt_json_filter':JSON.stringify({'badge_id_array':[18,16],'referral_id_array_in':objectArray}) }; var dummy = []; $scope.data_product_done = false; GAEAPI.get('product/lists',d,$scope).then(function(e){ if(e.ok === 1){ $scope.data_product = e.data.dataList; $scope.data_product_done = true; angular.forEach($scope.data, function(item,key){ item.referral_feature_name = $scope.dummyFeatureName; item.referral_product_array = e.data.dataList; item.referral_image_all_array = $scope.dummyReferralImage; }); console.log("getDataProductByReferralArray: referral data",$scope.data); console.log("getDataProductByReferralArray: referral_id_array_in",objectArray); console.log("getDataProductByReferralArray: params",d); console.log("getDataProductByReferralArray: data",e); } }); }; /* Get referral data (by referral_id) * @params id = referral_id * @return array */ $scope.getDataReferral = function(id){ $scope.data = []; $scope.data_done = false; var d = { 'txt_referral_id':id }; GAEAPI.get('referral/id_map',d,$scope).then(function(e){ if(e.ok == 1){ $scope.data[0] = e.data; $scope.data_done = true; $scope.buildImageSlider($scope.data); } }); }; /* * params listener * @params newValue * @params oldValue * @return function */ $scope.$watch('use_auto', function (newValue, oldValue) { if (!newValue && typeof $scope.referralid !== 'undefined' && $scope.referralid !== ''){ return $scope.getDataReferral($scope.referralid); } $scope.getData(); }); /* * check if image array exist or build dummy image array * @params arrayObject = object array * @return array */ $scope.dummyArrayImageGallery = [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_2.png'}, ]; $scope.buildImageSlider = function(){ var imageArray = function(idx){ if(idx == 0){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1.jpg'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'}, ]; } else if(idx == 1){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1_2.png'}, ]; } else { return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'}, ]; } }; var imageBannerArray = function(idx){ if(idx == 0){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1.jpg'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2.jpg'}, ]; } else if(idx == 1) { return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1_2.png'}, ]; } else { return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2_1.png'}, {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2_2.png'}, ]; } }; angular.forEach($scope.data, function(item, key){ if(!item.referral_image.length){ item.referral_image = imageArray(key); } item.referral_image_banner = imageBannerArray(key); }); }; /* Make Carousel */ $scope._makeProductToCarousel = function (keyCustom, type) { var elementName = '[data-id="' + keyCustom + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, "", keyCustom); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(){ return "-" + (($('.row.slick-slider[data-id="'+$scope._uniqueKey+'"]').height() / 2) + 34) + "px"; }; /* Carousel Arrow Click */ $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; /* Carousel Arrow Click */ $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { $timeout(function(){ if($('.gallery-block[data-id]').length){ $('.gallery-block[data-id]').not('.slick-initialized').each(function(Key,Object){ if($(this).find('.imageItem').length > 0){ $scope._makeProductToCarousel($(this).attr('data-id'), 'gallery'); } }); } },500); }); /*angular.element($window).bind('load', function(){*/ if($location.path() == '/' || $location.path() == '/home'){ var checkSliderImageProduct = setInterval(function(){ console.log("checking...", $('.cart-block').not('.slick-initialized').length); if($('.cart-block.slick-initialized').length == $('.cart-block').length && $scope.data_product.length > 0){ clearInterval(checkSliderImageProduct); return; } else { $('.cart-block').not('.slick-initialized').each(function(){ if($(this).find('.row-product').length){ var elementName = '[data-id="' + $(this).data('id') + '"]'; var paramsOptions = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; sliderProvider(elementName, paramsOptions, "", $(this).data('id')); } }); } },1000); } /*});*/ /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; /* Open Link in other windows */ $scope.openWindows = function(stringUrl){ return window.open(stringUrl, '_blank', 'location=yes,height='+$(window).height()+',width='+$(window).width()+',scrollbars=yes,status=yes'); }; }; return promise; }); _ui_share_app.directive('componentCategoryLanding', function ($rootScope, $routeParams, $location) { var templateName = 'componentCategoryLanding'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.viewRouteParams=function(){ return $routeParams || false; }; $scope.data = []; $scope.data_none_multi = []; $scope.data_multi = []; $scope.data_parent = false; $scope.data_load = false; $scope.getData=function(){ $scope.data = []; $scope.data_none_multi = []; $scope.data_multi = []; if(typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != 0){ var d = {'txt_referral_type_id':11,'txt_parent_id':$routeParams.referral_id}; } else { var d = {'txt_referral_type_id':11}; } GAEAPI.get('referral/map',d).then(function(e){ if(e.data.length > 0){ $scope.data = e.data; console.log("category-landing : no",d,e); angular.forEach($scope.data, function(item){ if(item.referral_sub_array.length > 0){ $scope.data_multi.push(item); $scope.data_load = true; } else { $scope.data_none_multi.push(item); $scope.getParentData(item.referral_parent_id); $scope.data_load = true; } }); } else { $timeout(function(){ $scope.data_load = true; },2000); $scope.matchReferral.root_id=''; $scope.matchReferral.referral_parent_id=''; $scope.matchReferral.referral_id=''; console.log("category-landing : new", $routeParams.referral_id); return $scope.getRelation($routeParams.referral_id); } }); }; $scope.getData(); $scope.getParentData = function(id){ if($scope.data_parent==false){ var d = {'txt_referral_id':id}; GAEAPI.get('referral/id',d).then(function(e){ if(e.ok == 1){ $scope.data_parent = e.data; } }); } }; $scope.$watch('data_none_multi',function(newValue,oldValue){ if(!newValue.length || !newValue){ return; } }); $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); }; $scope.relation = []; $scope.matchReferral = { root_id:'', referral_parent_id:'', referral_id:'', }; $scope.matchCount = 0; $scope.getRelation = function(refId){ console.log("category-landing: getRelation", refId); $scope.matchReferral.referral_id = refId; $scope.matchCount = $scope.matchCount+1; GAEAPI.get('referral/relation',{'txt_referral_id':refId}).then(function(e){ if(e.data.length){ /*$scope.relation = e.data;*/ var first = 0; var last = e.data.length - 1; console.log("category-landing: e.data", e.data); console.log("category-landing: fist-last", first, last); if(parseInt(e.data[first].referral_parent_id) <= 0){ console.log("category-landing: root_id", e.data[first].referral_id); console.log("category-landing: -root_id",parseInt(e.data[first].referral_parent_id)); $scope.matchReferral.root_id = e.data[first].referral_id; $scope.matchCount = $scope.matchCount+1; } if(parseInt(e.data[last].referral_parent_id) > 0){ console.log("category-landing: referral_parent_id", e.data[last].referral_parent_id); console.log("category-landing: -referral_parent_id", parseInt(e.data[last].referral_parent_id)); $scope.matchReferral.referral_parent_id = e.data[last].referral_parent_id; $scope.matchCount = $scope.matchCount+1; } } }); }; $scope.$watch('matchCount',function(newValue,oldValue){ console.log("category-landing: matchCount", newValue); if(newValue >= 2){ console.log("category-landing: matchCount : ready", $scope.matchReferral); $timeout(function(){ window.location.href="category-lists?root_id="+$scope.matchReferral.root_id+"&referral_parent_id="+$scope.matchReferral.referral_parent_id+"&referral_id="+$scope.matchReferral.referral_id+"&referral_type=category"; },100); } }); }; return promise; }); _ui_share_app.directive('componentCategoryLandingB', function ($rootScope, $routeParams, $location) { var templateName = 'componentCategoryLandingB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.viewRouteParams=function(){ return $routeParams || false; }; $scope._params = $routeParams.referral_id; $scope.data = []; $scope.data_none_multi = []; $scope.data_multi = []; $scope.data_parent = false; $scope.data_load = false; $scope.getData=function(){ $scope.data = []; $scope.data_none_multi = []; $scope.data_multi = []; if(typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != 0){ var d = {'txt_referral_type_id':11,'txt_parent_id':$routeParams.referral_id}; } else { var d = {'txt_referral_type_id':11}; } GAEAPI.get('referral/map',d).then(function(e){ if(e.data.length > 0){ $scope.data = e.data; console.log("category-landing : no",d,e); angular.forEach($scope.data, function(item){ if(item.referral_sub_array.length > 0){ $scope.data_multi.push(item); $scope.data_load = true; } else { $scope.data_none_multi.push(item); $scope.getParentData(item.referral_parent_id); $scope.data_load = true; } }); } else { $timeout(function(){ $scope.data_load = true; },2000); $scope.matchReferral.root_id=''; $scope.matchReferral.referral_parent_id=''; $scope.matchReferral.referral_id=''; console.log("category-landing : new", $routeParams.referral_id); return $scope.getRelation($routeParams.referral_id); } }); }; $scope.getData(); $scope.getParentData = function(id){ if($scope.data_parent==false){ var d = {'txt_referral_id':id}; GAEAPI.get('referral/id',d).then(function(e){ if(e.ok == 1){ $scope.data_parent = e.data; } }); } }; $scope._data_referral_relate_ = []; $scope._get_referral_relate_ = function (array) { var dataSend = { 'txt_referral_id': array, }; GAEAPI.get('referral/relation', dataSend).then(function (e) { if (e.ok === 1) { $scope._data_referral_relate_ = e.data; } }); }; $scope.$watch('data_none_multi',function(newValue,oldValue){ if(!newValue.length || !newValue){ return; } }); $scope.$watch('_params', function(newValue, oldValue) { if(newValue){ $scope._get_referral_relate_(newValue); } if (!newValue) return; }); $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); }; $scope.relation = []; $scope.matchReferral = { root_id:'', referral_parent_id:'', referral_id:'', }; $scope.matchCount = 0; $scope.getRelation = function(refId){ console.log("category-landing: getRelation", refId); $scope.matchReferral.referral_id = refId; $scope.matchCount = $scope.matchCount+1; GAEAPI.get('referral/relation',{'txt_referral_id':refId}).then(function(e){ if(e.data.length){ /*$scope.relation = e.data;*/ var first = 0; var last = e.data.length - 1; console.log("category-landing: e.data", e.data); console.log("category-landing: fist-last", first, last); if(parseInt(e.data[first].referral_parent_id) <= 0){ console.log("category-landing: root_id", e.data[first].referral_id); console.log("category-landing: -root_id",parseInt(e.data[first].referral_parent_id)); $scope.matchReferral.root_id = e.data[first].referral_id; $scope.matchCount = $scope.matchCount+1; } if(parseInt(e.data[last].referral_parent_id) > 0){ console.log("category-landing: referral_parent_id", e.data[last].referral_parent_id); console.log("category-landing: -referral_parent_id", parseInt(e.data[last].referral_parent_id)); $scope.matchReferral.referral_parent_id = e.data[last].referral_parent_id; $scope.matchCount = $scope.matchCount+1; } } }); }; $scope.$watch('matchCount',function(newValue,oldValue){ console.log("category-landing: matchCount", newValue); if(newValue >= 2){ console.log("category-landing: matchCount : ready", $scope.matchReferral); $timeout(function(){ window.location.href="category-lists?root_id="+$scope.matchReferral.root_id+"&referral_parent_id="+$scope.matchReferral.referral_parent_id+"&referral_id="+$scope.matchReferral.referral_id+"&referral_type=category"; },100); } }); }; return promise; }); _ui_share_app.directive('componentCategoryLandingC', function($rootScope, $routeParams, $location) { var templateName = 'componentCategoryLandingC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window) { $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.data = []; $scope.data_none_multi = []; $scope.data_multi = []; $scope.data_parent = false; $scope.data_load = false; $scope.getData = function() { $scope.data = []; $scope.data_none_multi = []; $scope.data_multi = []; if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': $routeParams.referral_id }; } else { var d = { 'txt_referral_type_id': 11 }; } GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.data.length > 0) { $scope.data = e.data; console.log("category-landing : no", d, e); angular.forEach($scope.data, function(item) { if (item.referral_sub_array.length > 0) { $scope.data_multi.push(item); $scope.data_load = true; } else { $scope.data_none_multi.push(item); $scope.getParentData(item.referral_parent_id); $scope.data_load = true; } }); } else { $timeout(function() { $scope.data_load = true; }, 300); $scope.matchReferral.root_id = ''; $scope.matchReferral.referral_parent_id = ''; $scope.matchReferral.referral_id = ''; console.log("category-landing : new", $routeParams.referral_id); return $scope.getRelation($routeParams.referral_id); } }); }; $scope.getData(); $scope.getParentData = function(id) { if ($scope.data_parent == false) { var d = { 'txt_referral_id': id }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data_parent = e.data; } }); } }; // $scope.$watch('data_none_multi',function(newValue,oldValue){ // if(!newValue.length || !newValue){ // return; // } // }); $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); }; $scope.relation = []; $scope.matchReferral = { root_id: '', referral_parent_id: '', referral_id: '', referral_name: '', }; $scope.matchCount = 0; $scope.getRelation = function(refId) { console.log("category-landing: getRelation", refId); $scope.matchReferral.referral_id = refId; $scope.matchReferral.referral_name = $scope.viewRouteParams().referral_name; $scope.matchCount = $scope.matchCount + 1; GAEAPI.get('referral/relation', { 'txt_referral_id': refId }, $scope).then(function(e) { if (e.data.length) { /*$scope.relation = e.data;*/ var first = 0; var last = e.data.length - 1; console.log("category-landing: e.data", e.data); console.log("category-landing: fist-last", first, last); if (parseInt(e.data[first].referral_parent_id) <= 0) { console.log("category-landing: root_id", e.data[first].referral_id); console.log("category-landing: -root_id", parseInt(e.data[first].referral_parent_id)); $scope.matchReferral.root_id = e.data[first].referral_id; $scope.matchCount = $scope.matchCount + 1; } if (parseInt(e.data[last].referral_parent_id) > 0) { console.log("category-landing: referral_parent_id", e.data[last].referral_parent_id); console.log("category-landing: -referral_parent_id", parseInt(e.data[last].referral_parent_id)); $scope.matchReferral.referral_parent_id = e.data[last].referral_parent_id; $scope.matchCount = $scope.matchCount + 1; } } }); }; $scope.$watch('matchCount', function(newValue, oldValue) { console.log("category-landing: matchCount", newValue); if (newValue >= 2) { console.log("category-landing: matchCount : ready", $scope.matchReferral); $timeout(function() { var url = "category-lists?root_id=" + $scope.matchReferral.root_id + "&referral_parent_id=" + $scope.matchReferral.referral_parent_id + "&referral_id=" + $scope.matchReferral.referral_id + "&referral_type=category" + "&referral_name=" + $scope.matchReferral.referral_name; $location.url(url).replace(); // window.location.href = "category-lists?root_id=" + $scope.matchReferral.root_id + "&referral_parent_id=" + $scope.matchReferral.referral_parent_id + "&referral_id=" + $scope.matchReferral.referral_id + "&referral_type=category" + "&referral_name=" + $scope.matchReferral.referral_name; }, 100); } }); }; return promise; }); _ui_share_app.directive('componentCategoryLandingD', function ($rootScope, $routeParams, $location) { var templateName = 'componentCategoryLandingD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.viewRouteParams=function(){ return $routeParams || false; }; $scope._params = $routeParams.referral_id; $scope.data = []; $scope.data_none_multi = []; $scope.data_multi = []; $scope.data_parent = false; $scope.data_load = false; $scope.getData=function(){ $scope.data = []; $scope.data_none_multi = []; $scope.data_multi = []; if(typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != 0){ var d = {'txt_referral_type_id':11,'txt_parent_id':$routeParams.referral_id}; } else { var d = {'txt_referral_type_id':11}; } GAEAPI.get('referral/map',d , $scope).then(function(e){ if(e.data.length > 0){ $scope.data = e.data; console.log("category-landing : no",d,e); angular.forEach($scope.data, function(item){ if(item.referral_sub_array.length > 0){ $scope.data_multi.push(item); $scope.data_load = true; } else { $scope.data_none_multi.push(item); $scope.getParentData(item.referral_parent_id); $scope.data_load = true; } }); } else { $timeout(function(){ $scope.data_load = true; },2000); $scope.matchReferral.root_id=''; $scope.matchReferral.referral_parent_id=''; $scope.matchReferral.referral_id=''; console.log("category-landing : new", $routeParams.referral_id); return $scope.getRelation($routeParams.referral_id); } }); }; $scope.getData(); $scope.getParentData = function(id){ if($scope.data_parent==false){ var d = {'txt_referral_id':id}; GAEAPI.get('referral/id',d , $scope).then(function(e){ if(e.ok == 1){ $scope.data_parent = e.data; } }); } }; $scope._data_referral_relate_ = []; $scope._get_referral_relate_ = function (array) { var dataSend = { 'txt_referral_id': array, }; GAEAPI.get('referral/relation', dataSend ,$scope).then(function (e) { if (e.ok === 1) { $scope._data_referral_relate_ = e.data; } }); }; $scope.$watch('data_none_multi',function(newValue,oldValue){ if(!newValue.length || !newValue){ return; } }); $scope.$watch('_params', function(newValue, oldValue) { if(newValue){ $scope._get_referral_relate_(newValue); } if (!newValue) return; }); $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); }; $scope.relation = []; $scope.matchReferral = { root_id:'', referral_parent_id:'', referral_id:'', }; $scope.matchCount = 0; $scope.getRelation = function(refId){ console.log("category-landing: getRelation", refId); $scope.matchReferral.referral_id = refId; $scope.matchCount = $scope.matchCount+1; GAEAPI.get('referral/relation',{'txt_referral_id':refId},$scope).then(function(e){ if(e.data.length){ /*$scope.relation = e.data;*/ var first = 0; var last = e.data.length - 1; console.log("category-landing: e.data", e.data); console.log("category-landing: fist-last", first, last); if(parseInt(e.data[first].referral_parent_id) <= 0){ console.log("category-landing: root_id", e.data[first].referral_id); console.log("category-landing: -root_id",parseInt(e.data[first].referral_parent_id)); $scope.matchReferral.root_id = e.data[first].referral_id; $scope.matchCount = $scope.matchCount+1; } if(parseInt(e.data[last].referral_parent_id) > 0){ console.log("category-landing: referral_parent_id", e.data[last].referral_parent_id); console.log("category-landing: -referral_parent_id", parseInt(e.data[last].referral_parent_id)); $scope.matchReferral.referral_parent_id = e.data[last].referral_parent_id; $scope.matchCount = $scope.matchCount+1; } } }); }; $scope.$watch('matchCount',function(newValue,oldValue){ console.log("category-landing: matchCount", newValue); if(newValue >= 2){ console.log("category-landing: matchCount : ready", $scope.matchReferral); $timeout(function(){ window.location.href="category-lists?root_id="+$scope.matchReferral.root_id+"&referral_parent_id="+$scope.matchReferral.referral_parent_id+"&referral_id="+$scope.matchReferral.referral_id+"&referral_type=category"; },100); } }); }; return promise; }); _ui_share_app.directive('componentCategoryMenuDropdown', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCategoryMenuDropdown'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) {}; promise.controller = function ($scope, $timeout, $interval, $window, $http) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.myFunctionDropdown = function () { document.getElementById("myDropdown").classList.toggle("show"); } $scope.onclick = function (event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } $scope._page_lists = false; $scope._page_lists_load = false; $scope._get_page_lists = function () { $scope._clear_page_lists(); var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'page_lastest_create' }; GAEAPI.get('page/lists', dataSend ,$scope).then(function (res) { $scope._page_lists_load = true; if (res.ok === 1) { $scope._page_lists = res.data.dataList; angular.forEach($scope._page_lists, function (item, key) { if (item.page_search_url == "") { item.page_search_url = item.page_id; } }); } }); }; $scope._clear_page_lists = function () { $scope._page_lists = false; $scope._page_lists_load = false; }; /*$scope._get_page_lists();*/ /*$scope._page_category = (typeof window.referralMap !== 'undefined') ? window.referralMap.data : false;*/ $scope._page_category_load = false; $scope._get_page_category = function () { /*$scope._clear_page_lists(); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', dataSend).then(function(res) { $scope._page_category_load = true; if (res.ok === 1) { $scope._page_category = res.data; } });*/ }; $scope._clear_page_category = function () { $scope._page_category = false; $scope._page_category_load = false; }; /*$scope._get_page_category();*/ $scope.requestApiArray = []; $scope.chainRerrealRequest = function (txt_referral_type_id, txt_parent_id, callbackData, childCount) { var dataSend = { 'cur_page': 1, 'per_page': (txt_parent_id <= 0) ? 20 : childCount, 'txt_referral_type_id': txt_referral_type_id, 'txt_parent_id': txt_parent_id, 'txt_badge_id': 18, 'txt_sortby' : 'referral_sort_index_asc_name_asc', 'base_shop_name': 'myhappyphone', }; if (parseInt(txt_referral_type_id) > 0) { dataSend.txt_view_referral_child = 1; } $http.get(GURL.base_api_url() + 'referral/short_lists', {params: dataSend} , $scope).then(function (res) { $scope.requestApiArray[txt_referral_type_id] = $timeout(function () { var e = res.data; if (e.ok === 1) { if (typeof callbackData == undefined || callbackData == undefined) { $scope._page_category = e.data.dataList; $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); } else { $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); return callbackData(e); } } }, 20); }); }; $scope.chainRerrealRequest(11, 0); $scope.chainReferralHover = function (objectParent, level) { console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_count); if (objectParent.referral_sub_count > 0 && objectParent.referral_sub_array.length <= 0) { $scope.chainRerrealRequest(11, objectParent.referral_id, function (e) { if (e.ok === 1 && e.data.dataList.length) { objectParent.referral_sub_array = e.data.dataList; console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_array); } }, objectParent.referral_sub_count); } }; }; return promise; });_ui_share_app.directive('componentCategoryMenuDropdownAa', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCategoryMenuDropdownAa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s.toLowerCase(); }; $scope.dropdown = false; $scope.myFunctionDropdown = function() { document.getElementById("myDropdown").classList.toggle("show"); var dropdown = $(".dropdown-menu").height() + 11; console.log("myFunctionDropdown - content : ", dropdown); $('.dropdown-menu').css('min-height', dropdown); }; $("#myDropdown").mouseenter(function() {}).mouseleave(function() { document.getElementById("myDropdown").classList.toggle("show"); var dropdown = $(".dropdown-menu").height() + 11; console.log("myFunctionDropdown - content : ", dropdown); $('.dropdown-menu').css('min-height', dropdown); }); $scope.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } }; $scope._page_lists = false; $scope._page_lists_load = false; $scope._get_page_lists = function() { $scope._clear_page_lists(); var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'page_lastest_create' }; GAEAPI.get('page/lists', dataSend, $scope).then(function(res) { $scope._page_lists_load = true; if (res.ok === 1) { $scope._page_lists = res.data.dataList; angular.forEach($scope._page_lists, function(item, key) { if (item.page_search_url == "") { item.page_search_url = item.page_id; } }); } }); }; $scope._clear_page_lists = function() { $scope._page_lists = false; $scope._page_lists_load = false; }; /*$scope._get_page_lists();*/ /*$scope._page_category = (typeof window.referralMap !== 'undefined') ? window.referralMap.data : false;*/ $scope._page_category_load = false; $scope._get_page_category = function() { /*$scope._clear_page_lists(); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', dataSend).then(function(res) { $scope._page_category_load = true; if (res.ok === 1) { $scope._page_category = res.data; } });*/ }; $scope._clear_page_category = function() { $scope._page_category = false; $scope._page_category_load = false; }; /*$scope._get_page_category();*/ $scope.requestApiArray = []; $scope.chainRerrealRequest = function(txt_referral_type_id, txt_parent_id, callbackData, childCount) { var dataSend = { 'cur_page': 1, 'per_page': (txt_parent_id <= 0) ? 20 : childCount, 'txt_referral_type_id': txt_referral_type_id, 'txt_parent_id': txt_parent_id, 'txt_badge_id': 18, 'txt_sortby': 'referral_sort_index_asc_name_desc', 'base_shop_name': 'proplugin', }; if (parseInt(txt_referral_type_id) > 0) { dataSend.txt_view_referral_child = 1; } $http.get(GURL.base_api_url() + 'referral/short_lists', { params: dataSend }, $scope).then(function(res) { console.log("chainRerrealRequest : dataSend : ", dataSend); $scope.requestApiArray[txt_referral_type_id] = $timeout(function() { var e = res.data; console.log("chainRerrealRequest : e : ", e); if (e.ok === 1) { if (typeof callbackData == undefined || callbackData == undefined) { $scope._page_category = e.data.dataList; $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); } else { $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); return callbackData(e); } } }, 20); }); }; $scope.chainRerrealRequest(11, 0); $scope.chainReferralHover = function(objectParent, level) { console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_count); if (objectParent.referral_sub_count > 0 && objectParent.referral_sub_array.length <= 0) { $scope.chainRerrealRequest(11, objectParent.referral_id, function(e) { if (e.ok === 1 && e.data.dataList.length) { objectParent.referral_sub_array = e.data.dataList; console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_array); } }, objectParent.referral_sub_count); } }; }; return promise; });_ui_share_app.directive('componentCategoryMenuDropdownAb', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCategoryMenuDropdownAb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s.toLowerCase(); }; $scope.dropdown = false; $scope.myFunctionDropdown = function() { document.getElementById("myDropdown").classList.toggle("show"); }; $("#myDropdown").mouseenter(function() {}).mouseleave(function() { document.getElementById("myDropdown").classList.toggle("show"); }); $scope.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } }; $scope._page_lists = false; $scope._page_lists_load = false; $scope._get_page_lists = function() { $scope._clear_page_lists(); var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'page_lastest_create' }; GAEAPI.get('page/lists', dataSend, $scope).then(function(res) { $scope._page_lists_load = true; if (res.ok === 1) { $scope._page_lists = res.data.dataList; angular.forEach($scope._page_lists, function(item, key) { if (item.page_search_url == "") { item.page_search_url = item.page_id; } }); } }); }; $scope._clear_page_lists = function() { $scope._page_lists = false; $scope._page_lists_load = false; }; /*$scope._get_page_lists();*/ /*$scope._page_category = (typeof window.referralMap !== 'undefined') ? window.referralMap.data : false;*/ $scope._page_category_load = false; $scope._get_page_category = function() { /*$scope._clear_page_lists(); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', dataSend).then(function(res) { $scope._page_category_load = true; if (res.ok === 1) { $scope._page_category = res.data; } });*/ }; $scope._clear_page_category = function() { $scope._page_category = false; $scope._page_category_load = false; }; /*$scope._get_page_category();*/ $scope.requestApiArray = []; $scope.chainRerrealRequest = function(txt_referral_type_id, txt_parent_id, callbackData, childCount) { var dataSend = { 'cur_page': 1, 'per_page': (txt_parent_id <= 0) ? 20 : childCount, 'txt_referral_type_id': txt_referral_type_id, 'txt_parent_id': txt_parent_id, 'txt_badge_id': 18, 'base_shop_name': 'supercheap' }; if (parseInt(txt_referral_type_id) > 0) { dataSend.txt_view_referral_child = 1; } $http.get(GURL.base_api_url() + 'referral/short_lists', { params: dataSend }, $scope).then(function(res) { $scope.requestApiArray[txt_referral_type_id] = $timeout(function() { var e = res.data; if (e.ok === 1) { if (typeof callbackData == undefined || callbackData == undefined) { $scope._page_category = e.data.dataList; $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); } else { $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); return callbackData(e); } } }, 20); }); }; $scope.chainRerrealRequest(11, 0); $scope.chainReferralHover = function(objectParent, level) { console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_count); if (objectParent.referral_sub_count > 0 && objectParent.referral_sub_array.length <= 0) { $scope.chainRerrealRequest(11, objectParent.referral_id, function(e) { if (e.ok === 1 && e.data.dataList.length) { objectParent.referral_sub_array = e.data.dataList; console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_array); } }, objectParent.referral_sub_count); } }; }; return promise; });_ui_share_app.directive('componentCategoryMenuDropdownAc', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCategoryMenuDropdownAc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { category: '@category', imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.forbidden = false; $scope.$watch('category', function(newCategory, oldCategory) { $scope.newCat = (newCategory == undefined || newCategory == '') ? 'หมวดหมู่' : newCategory; $scope.oldCat = oldCategory; }); $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s.toLowerCase(); }; $scope.dropdown = false; $scope.myFunctionDropdown = function() { document.getElementById("myDropdown").classList.toggle("show"); var dropdown = $(".dropdown-menu").height() + 11; console.log("myFunctionDropdown - content : ", dropdown); $('.dropdown-menu').css('min-height', dropdown); }; $("#myDropdown").mouseenter(function() {}).mouseleave(function() { document.getElementById("myDropdown").classList.toggle("show"); var dropdown = $(".dropdown-menu").height() + 11; console.log("myFunctionDropdown - content : ", dropdown); $('.dropdown-menu').css('min-height', dropdown); }); $scope.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } }; $scope.requestApiArray = []; $scope.chainRerrealRequest = function(txt_referral_type_id, txt_parent_id, callbackData, childCount) { var dataSend = { 'cur_page': 1, 'per_page': (txt_parent_id <= 0) ? 20 : childCount, 'txt_referral_type_id': txt_referral_type_id, 'txt_parent_id': txt_parent_id, 'txt_badge_id': 18, 'txt_sortby': 'referral_sort_index_asc_name_desc', 'base_shop_name': 'bypshop', }; if (parseInt(txt_referral_type_id) > 0) { dataSend.txt_view_referral_child = 1; } $http.get(GURL.base_api_url() + 'referral/short_lists', { params: dataSend }, $scope).then(function(res) { console.log("chainRerrealRequest : dataSend : ", dataSend); $scope.requestApiArray[txt_referral_type_id] = $timeout(function() { var e = res.data; console.log("chainRerrealRequest : e : ", e); if (e.ok === 1) { if (typeof callbackData == undefined || callbackData == undefined) { $scope._page_category = e.data.dataList; $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); } else { $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); return callbackData(e); } } }, 20); }); }; $scope.chainRerrealRequest(11, 0); $scope.chainReferralHover = function(objectParent, level) { console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_count); if (objectParent.referral_sub_count > 0 && objectParent.referral_sub_array.length <= 0) { $scope.chainRerrealRequest(11, objectParent.referral_id, function(e) { if (e.ok === 1 && e.data.dataList.length) { objectParent.referral_sub_array = e.data.dataList; console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_array); } }, objectParent.referral_sub_count); } }; }; return promise; });_ui_share_app.directive('componentCategoryMenuDropdownAd', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCategoryMenuDropdownAd'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s.toLowerCase(); }; $scope.dropdown = false; $scope.myFunctionDropdown = function() { document.getElementById("myDropdown").classList.toggle("show"); var dropdown = $(".dropdown-menu").height() + 11; console.log("myFunctionDropdown - content : ", dropdown); $('.dropdown-menu').css('min-height', dropdown); }; $("#myDropdown").mouseenter(function() {}).mouseleave(function() { document.getElementById("myDropdown").classList.toggle("show"); var dropdown = $(".dropdown-menu").height() + 11; console.log("myFunctionDropdown - content : ", dropdown); $('.dropdown-menu').css('min-height', dropdown); }); $scope.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } }; $scope.requestApiArray = []; $scope.chainRerrealRequest = function(txt_referral_type_id, txt_parent_id, callbackData, childCount) { var dataSend = { 'cur_page': 1, 'per_page': (txt_parent_id <= 0) ? 20 : childCount, 'txt_referral_type_id': txt_referral_type_id, 'txt_parent_id': txt_parent_id, 'txt_badge_id': 18, 'txt_sortby': 'referral_sort_index_asc_name_desc', 'base_shop_name': 'maeju', }; if (parseInt(txt_referral_type_id) > 0) { dataSend.txt_view_referral_child = 1; } $http.get(GURL.base_api_url() + 'referral/short_lists', { params: dataSend }, $scope).then(function(res) { console.log("chainRerrealRequest : dataSend : ", dataSend); $scope.requestApiArray[txt_referral_type_id] = $timeout(function() { var e = res.data; console.log("chainRerrealRequest : e : ", e); if (e.ok === 1) { if (typeof callbackData == undefined || callbackData == undefined) { $scope._page_category = e.data.dataList; $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); } else { $timeout.cancel($scope.requestApiArray[txt_referral_type_id]); return callbackData(e); } } }, 20); }); }; $scope.chainRerrealRequest(11, 0); $scope.chainReferralHover = function(objectParent, level) { console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_count); if (objectParent.referral_sub_count > 0 && objectParent.referral_sub_array.length <= 0) { $scope.chainRerrealRequest(11, objectParent.referral_id, function(e) { if (e.ok === 1 && e.data.dataList.length) { objectParent.referral_sub_array = e.data.dataList; console.log(objectParent.referral_name, ' child => ', objectParent.referral_sub_array); } }, objectParent.referral_sub_count); } }; }; return promise; }); _ui_share_app.directive('componentCategorySetSlide', function ($rootScope, $routeParams) { var templateName = 'componentCategorySetSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.category_All18 = []; $scope.get_category_All18 = function () { var txt_filter_json = { 'badge_id_array': [18] }; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_name_a-z', 'txt_filter_json': JSON.stringify(txt_filter_json), }; GAEAPI.get('referral/map', dataSend , $scope).then(function (res) { if (res.ok === 1) { $scope.category_All18 = res.data; console.log("esdoiwpfel :", $scope.category_All18); } }); }; $scope.get_category_All18(); $scope.testaa = ''; $scope.ykey =function(refid){ var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': refid, }; GAEAPI.get('referral/map', dataSend, $scope).then(function (res) { if(res.ok != 1){ return; } if(res.data.length > 0){ $scope.testaa = 'yes'; return $scope.testaa; }else{ $scope.testaa = 'no'; return $scope.testaa; } }); }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Check if child array exist */ $scope.checkChild = function(object){ return (!object.referral_sub_array.length) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentCategorySlideHome', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentCategorySlideHome'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', margin:'@margin', name: '@name', refid: '@refid', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 6; i++){ r.push({ banner_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/180x150.jpg'}], callback_array:true }); } return r; }; $scope.$watch('refid',function(newValue,oldValue){ if(newValue){ $scope.getdata(newValue); } }); $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'categoryslide'; $scope.done = false; $scope.prev_win_size = $(window).width(); $scope.getdata = function(newvalue){ var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': newvalue, }; GAEAPI.get('referral/map', dataSend, $scope).then(function (res) { if(res.ok != 1){ return; } if(res.data.length > 0){ $scope.data = res.data; }else{ $scope.data = []; $scope.getproductdata(newvalue); } }); }; $scope.data_product = []; $scope.getproductdata = function(referal_id){ var txt_filter_json = { 'referral_id_array': [referal_id], 'badge_id_array':[18], }; var data_sent = { 'cur_page': 1, 'per_page': 12, 'txt_filter_json': JSON.stringify(txt_filter_json), }; GAEAPI.get('product/lists', data_sent , $scope).then(function (res) { if (res.ok === 1) { $scope.data_product = res.data.dataList; } }); }; $scope.viewData = function(){ return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 4, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ $window.location.href=i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if($('.component_carousel_map[data-id="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.initSlider(); }, 500); } }); $scope.checkHide = function(){ return ($('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length > 0) ? true : false; }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentClientImage', function ($rootScope, $routeParams) { var templateName = 'componentClientImage'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.directive('componentClientImageA', function ($rootScope, $routeParams) { var templateName = 'componentClientImageA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.factory('$componentCollection', function componentCollection($routeParams, $timeout) { return });_ui_share_app.directive('componentCollectionIdTypeA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCollectionIdTypeA'; var componentMain = 'componentCollection'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { col: '@col', component: '@component', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope._dataArray = []; $scope._dataTime = { start: 0, end: 0 }; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { console.log("CHECK COLLECTION READY "); $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_collection_id': id, }; GAEAPI.get('collection/id', dataSend).then(function(output) { console.log("CHECK COLLECTION START ", output); if (output.ok === 1) { var item = output.data; $scope._dataArray = item; $scope._dataTime.start = item.collection_lifetime.lifetime_start_time; $scope._dataTime.end = item.collection_lifetime.lifetime_end_time; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.collectionData = false; $scope.collectionDataSend = false; $scope.isLoadMore = false; $scope.isLoadMoreHide = false; $scope.getDetail = function(id) { var dataSend = { 'txt_collection_id': id, 'cur_page': ($scope.collectionDataSend) ? $scope.collectionDataSend.cur_page : 1, 'per_page': ($scope.collectionDataSend) ? $scope.collectionDataSend.per_page : 12, 'txt_badge_id': 18 }; $scope.collectionDataSend = dataSend; GAEAPI.get('collection/short_id', dataSend).then(function(e) { console.log("collection/id: res", e); if (dataSend.cur_page > 1) { var oldProductArray = $scope.collectionData.collection_product_array; var currentData = e.data.collection_product_array; var mergeProductArray = oldProductArray.concat(currentData); $scope.collectionData.collection_product_array = mergeProductArray; } else { $scope.collectionData = e.data; } $scope.isLoadMore = false; var maxPage = parseInt($scope.collectionData.collection_product_pagination.total_page); var nextPage = parseInt($scope.collectionData.collection_product_pagination.next_page); if (dataSend.cur_page >= maxPage) { $scope.isLoadMoreHide = true; } }); }; $scope.getDetail($scope._idUrl($scope._viewRouteParams().collection_id)); $scope.loadMore = function() { $scope.collectionDataSend.cur_page = $scope.collectionDataSend.cur_page + 1; $scope.isLoadMore = true; $timeout(function() { $scope.getDetail($scope._idUrl($scope._viewRouteParams().collection_id)); }, 100); }; $scope.timeHide = function(timestampStart, timestampEnd) { var dates = new Date().getTime(); var datesLen = dates.toString().length; var timeStart = String(timestampStart); var timeEnd = String(timestampEnd); var subdate = parseInt(dates.toString().substring(0, timeEnd.length)); var end = timestampEnd - subdate; return (timestampEnd == -1) ? 1 : end; }; $scope.timeReplace = function(timestampStart, timestampEnd) { var dates = new Date().getTime(); var datesLen = dates.toString().length; var timeStart = String(timestampStart); var timeEnd = String(timestampEnd); var subdate = parseInt(dates.toString().substring(0, timeEnd.length)); var end = timestampEnd - subdate; if (timestampEnd == -1) { end = 1; } if (end <= 0) { if ($scope._dataTime.end == "-1" || $scope._dataTime.end == -1) { return; } window.location.href = 'home'; } }; $scope.check = function() { return { start: function(inputTimeStamp) { var todayTimeStamp = (new Date().getTime() / 1000); var targetTimeStamp = parseInt(inputTimeStamp); return (targetTimeStamp <= todayTimeStamp) ? true : false; }, end: function(inputTimeStamp) { var todayTimeStamp = (new Date().getTime() / 1000); var targetTimeStamp = parseInt(inputTimeStamp); if (parseInt(targetTimeStamp) == -1) { return true; } return (targetTimeStamp > todayTimeStamp) ? true : false; }, } }; $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.dates = new Date(); $scope.timeReplace($scope._dataTime.start, $scope._dataTime.end); $scope.timeCountStart(); }, 1000); }; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.checkShop = function() { if (CUR_THEME.shop_id() == "646") { return 646; } else { return false; } }; $scope.showWeb = function(objArr) { var show = false; for (var i = 0; i < objArr.length; i++) { if (parseInt(objArr[i].badge_id) == 18) { show = true; break; } } return show; }; }; return promise; });_ui_share_app.directive('componentCollectionIdTypeB', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCollectionIdTypeB'; var componentMain = 'componentCollection'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewRouteParams = function() { return $routeParams; }; }; return promise; });_ui_share_app.directive('componentCollectionIdTypeC', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCollectionIdTypeC'; var componentMain = 'componentCollection'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', margin: '@margin', card: '@card', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $http) { $scope._component = { name: "componentCollectionIdTypeC", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._margin = ($scope.margin != undefined && $scope.margin != "") ? { margin: $scope.margin } : { margin: 0 }; $scope._card = ($scope.card != undefined && $scope.card != "") ? $scope.card : "c"; $scope._stylebutton = ($scope.stylebutton != undefined && $scope.stylebutton != "") ? $scope.stylebutton : "border_button_small"; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getCollectionId: function(params, callback) { var _self = this; var collection_id = (params.collection_id != undefined) ? params.collection_id.split("-", 1).join("") : false; _self.consoleLog("getBranchId", "collection_id", collection_id); callback(collection_id); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, main: function() { var _self = this; } } return getFunction; }; /* get api */ $scope.data_api = { load_more: { load: false, cur_page: 1, per_page: 12, total_rows: 0 }, collection_id: { data_send: {}, api: "collection/short_id", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.loadMore = function() { if (!$scope.data_api.load_more.load) { $scope.data_api.load_more.cur_page++; $scope.data_api.load_more.load = true; $scope.getData().getRouteParams(function(_self, params, state) { _self.getCollectionId(params, function(res_collection_id) { _self.formatDataSend($scope.data_api.collection_id, function(res_data) { var filter_json = {}; var dataSend = { 'txt_collection_id': res_collection_id, 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_badge_id': 18, 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.collection_product_array.length < res_api.data.collection_product_pagination.total_rows) { var oldData = res_data.data_array.collection_product_array; res_data.data_array.collection_product_array = oldData.concat(res_api.data.collection_product_array); $scope.data_api.load_more.total_rows = res_api.data.collection_product_pagination.total_rows; _self.consoleLog("getApiData", "res_data", res_data); } else { $scope.data_api.load_more.cur_page--; } $scope.data_api.load_more.load = false; }); }); }); }); }); } } $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.collection_id.data_array_state = state; _self.getCollectionId(params, function(res_collection_id) { _self.formatDataSend($scope.data_api.collection_id, function(res_data) { var filter_json = {}; var dataSend = { 'txt_collection_id': res_collection_id, 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_badge_id': 18, 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.collection_product_pagination.total_rows; }); }); }); }); }); /* get api */ }; return promise; });_ui_share_app.directive('componentCollectionSlideTypeA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCollectionSlideTypeA'; var componentMain = 'componentCollection'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { sortby: '@sortby', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', limit: '@limit', iconsize: '@iconsize', iconnext: '@iconnext', iconback: '@iconback', showresult: '@showresult', dots: '@dots', arrows: '@arrows', autoplay: '@autoplay', centermode: '@centermode', variablewidth: '@variablewidth', infinite: '@infinite', slidestoscroll: '@slidestoscroll', lg: '@lg', md: '@md', sm: '@sm', xs: '@xs', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limit = parseInt((typeof $scope.limit !== 'undefined' && typeof $scope.limit !== '') ? $scope.limit : 6); $scope._sortby = (typeof $scope.sortby !== 'undefined' && typeof $scope.sortby !== '') ? $scope.sortby : 'collection_create_time_DESC'; $scope._iconsize = (typeof $scope.iconsize !== 'undefined' && typeof $scope.iconsize !== '') ? $scope.iconsize : 30; $scope._iconback = (typeof $scope.iconback !== 'undefined' && typeof $scope.iconback !== '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = (typeof $scope.iconnext !== 'undefined' && typeof $scope.iconnext !== '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope._dots = Boolean((typeof $scope.dots !== 'undefined' && typeof $scope.dots !== '') ? $scope.dots : true); $scope._arrows = Boolean((typeof $scope.arrows !== 'undefined' && typeof $scope.arrows !== '') ? $scope.arrows : true); $scope._autoplay = Boolean((typeof $scope.autoplay !== 'undefined' && typeof $scope.autoplay !== '') ? $scope.autoplay : true); $scope._centerMode = Boolean((typeof $scope.centermode !== 'undefined' && typeof $scope.centermode !== '') ? $scope.centerMode : false); $scope._variableWidth = Boolean((typeof $scope.variablewidth !== 'undefined' && typeof $scope.variablewidth !== '') ? $scope.variablewidth : false); $scope._infinite = Boolean((typeof $scope.infinite !== 'undefined' && typeof $scope.infinite !== '') ? $scope.infinite : true); $scope._slidesToScroll = parseInt((typeof $scope.slidestoscroll !== 'undefined' && typeof $scope.slidestoscroll !== '') ? $scope.slidestoscroll : 4); $scope._col_lg = parseInt((typeof $scope.lg !== 'undefined' && typeof $scope.lg !== '') ? $scope.lg : 4); $scope._col_md = parseInt((typeof $scope.md !== 'undefined' && typeof $scope.md !== '') ? $scope.md : 3); $scope._col_sm = parseInt((typeof $scope.sm !== 'undefined' && typeof $scope.sm !== '') ? $scope.sm : 2); $scope._col_xs = parseInt((typeof $scope.xs !== 'undefined' && typeof $scope.xs !== '') ? $scope.xs : 1); $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getCollectionArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'cur_page': 1, 'per_page': $scope._limit, 'txt_sortby': $scope._sortby, }; console.log('dataSend_collection_short_lists', dataSend); GAEAPI.get('collection/short_lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getCollectionArray(); $scope.mkCarousel = function(elem) { $('.component-collection-slide-id-type-a').css('height', '0'); $('.component-collection-slide-id-type-a').css('opacity', '0'); console.log("col-lg-md-xs-sm : ", $scope._col_lg, $scope._col_md, $scope._col_xs, $scope._col_sm); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: $scope._dots, arrows: $scope._arrows, autoplay: $scope._autoplay, centerMode: $scope._centerMode, variableWidth: $scope._variableWidth, autoplaySpeed: 4000, slidesToShow: $scope._col_lg, slidesToScroll: 1, infinite: $scope._infinite, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: $scope._col_md, } }, { breakpoint: 991, settings: { slidesToShow: $scope._col_sm, } }, { breakpoint: 767, settings: { slidesToShow: $scope._col_xs, } }] }).closest('section').addClass('active'); $('.component-collection-slide-id-type-a').css('height', 'auto'); $('.component-collection-slide-id-type-a').css('opacity', '1'); }, 1500); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; });_ui_share_app.directive('componentCollectionTypeA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentCollectionTypeA'; var componentMain = 'componentCollection'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { curpage: '@curpage', perpage: '@perpage', txtsortby: '@txtsortby', col: '@col', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarousel = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 3 } }, { breakpoint: 768, settings: { slidesToShow: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'cur_page': (typeof $scope.curpage != 'undefined' && $scope.curpage != '') ? parseInt($scope.curpage) : 1, 'per_page': (typeof $scope.perpage != 'undefined' && $scope.perpage != '') ? parseInt($scope.perpage) : 5, 'txt_sortby': (typeof $scope.txtsortby != 'undefined' && $scope.txtsortby != '') ? $scope.txtsortby : 'collection_create_time_DESC', }; $scope._dataArray = []; GAEAPI.get('collection/short_lists', dataSend).then(function(output) { if (output.ok === 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.check = function() { return { start: function(inputTimeStamp) { var todayTimeStamp = (new Date().getTime() / 1000); var targetTimeStamp = parseInt(inputTimeStamp); return (targetTimeStamp <= todayTimeStamp) ? true : false; }, end: function(inputTimeStamp) { if (parseInt(inputTimeStamp) == -1) { return true; } var todayTimeStamp = (new Date().getTime() / 1000); var targetTimeStamp = parseInt(inputTimeStamp); return (targetTimeStamp > todayTimeStamp) ? true : false; }, } }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getDataArray(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.timeShow = function(timestampStart, timestampEnd) { if (typeof timestampStart === 'undefined' || typeof timestampEnd === 'undefined') { return false; } var dates = new Date().getTime(); var datesLen = dates.toString().length; var timeStart = timestampStart.toString(); var timeEnd = timestampEnd.toString(); var subdate = parseInt(dates.toString().substring(0, timestampStart.length)); var end = timestampEnd - subdate; return (subdate >= timestampStart) ? (end >= 0) ? true : (timestampEnd == -1) ? true : false : (timestampEnd == -1) ? true : fals; } $scope.timeTest = function(timestampStart, timestampEnd) { return timestampStart; }; $scope.timeHide = function(timestampStart, timestampEnd) { var dates = new Date().getTime(); var datesLen = dates.toString().length; var timeStart = timestampStart.toString(); var timeEnd = timestampEnd.toString(); var subdate = parseInt(dates.toString().substring(0, timeEnd.length)); var end = timestampEnd - subdate; return (timestampEnd == -1) ? 1 : end; }; $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.dates = new Date(); $scope.timeCountStart(); }, 1000); }; $scope.timeCountStart(); $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend-collection .-recommend-collection[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend-collection .-recommend-collection[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.viewDataSize = function() { return -($(".item-collection").height() + 100); }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.factory('$componentCollectionCard', function componentCollectionCard($routeParams, $timeout) { return });_ui_share_app.directive('componentCollectionCardA', function($rootScope, $routeParams) { var templateName = 'componentCollectionCardA'; var componentMain = 'componentCollectionCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '=datain', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentCollectionCardMain', function($rootScope, $routeParams) { var templateName = 'componentCollectionCardMain'; var componentMain = 'componentCollectionCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', dataout: '=datain', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; }); _ui_share_app.directive('componentCompareProduct', function ($rootScope, $routeParams) { var templateName = 'componentCompareProduct'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', param:'@param', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope._params = $routeParams.id; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (newValue){ $scope.getAllProduct(newValue); } }); /* * params listener * @params (default) * @return function */ /* * fetch product all * @params none * @return {Array} */ $scope.productArray = []; $scope.productArraycompare = []; $scope.getAllProduct = function (compare_param) { /* Set loading state */ /*$scope.productState.load = true; $scope.productState.done = false;*/ /* Begin Settingup Date */ var option = {}; var dataSend = { 'cur_page': 1, 'per_page': 100, }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { $scope.compare_id = compare_param.split(","); if (e.ok === 1) { $scope.productArray = e.data.dataList; console.log("compare_array 0 :" , $scope.productArray); for (var i = $scope.productArray.length - 1; i >= 0; i--) { for (var j = $scope.compare_id.length - 1; j >= 0; j--) { if($scope.productArray[i].product_id == $scope.compare_id[j]){ $scope.productArraycompare.push($scope.productArray[i]); } } } console.log("compare_array :" , $scope.productArraycompare); } }); }; $scope.set_param = function(index_id,index){ if($scope.productArraycompare.length > 1){ $scope.productArraycompare.splice(index,'1'); console.log("compare_array 3 :",$scope.productArraycompare); }else{ return; } }; }; return promise; }); _ui_share_app.directive('componentConfirmPayment', function($rootScope, $routeParams) { var templateName = 'componentConfirmPayment'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact: '@contact', name: '@name', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round'; $scope.language = ''; $scope.currentShopId = parseInt(CUR_THEME.shop_id()); $scope.shopIdlanguage = function() { switch ($scope.currentShopId) { case 541: /* TH */ $scope.language = 'th'; break; case 645: /* TH */ $scope.language = 'th'; break; case 646: /* TH */ $scope.language = 'th'; break; case 713: /* TH */ $scope.language = 'th'; break; case 718: /* TH */ $scope.language = 'th'; break; default: /* EN */ $scope.language = 'en'; break; } } $scope.shopIdlanguage(); $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; /* Watch Value */ $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else {} if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if (submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_contact', $scope.contact_email); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email-confirm-payment.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; }); _ui_share_app.directive('componentCover', function ($rootScope, $routeParams) { var templateName = 'componentCover'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.directive('componentCssForm', function () { var templateName = 'componentCssForm'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.link = function (scope, element, attr) { var t = null; var p = ''; function prev(element) { if (element.previousElementSibling) { return element.previousElementSibling; } var elm = element.previousSibling; while (elm != null && elm.nodeType !== 1) { elm = elm.previousSibling; } return elm; } function next(element) { if (element.nextElementSibling) { return element.nextElementSibling; } var elm = element.previousSibling; while (elm != null && elm.nodeType !== 1) { elm = elm.previousSibling; } return elm; } function emailValidate(email){ var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } scope.validateByType = function(evt){ var inputAttrType = evt.currentTarget.type; switch(inputAttrType){ case 'email': case 'Email': case 'EMAIL': if(!emailValidate(element.val()) && element.attr('required')){ element.removeClass('success'); element.removeClass('has_value'); next(evt.target).classList.remove('success'); next(evt.target).classList.remove('has_value'); element.addClass('error'); next(evt.target).classList.add('error'); console.log("email is not valid"); } else { console.log("email is valid"); } break; default: console.log("email is not match: evt", evt); console.log("email is not match: type", inputAttrType); break; } }; element.bind('focus',function(evt){ if(element.attr("placeholder") != ""){ if(p==""){ p = element.attr("placeholder"); } element.attr("old-placeholder", p); element.attr("placeholder",""); } if(element.attr('label')!=0||!element.attr("label")){ prev(evt.target).classList.add('label_is_active'); } if(element.val()!=""){ element.addClass("has_value"); } /*scope.validateByType(evt);*/ }); element.bind('blur', function(evt){ if(element.val() == ""){ if(element.attr('label')!=0||!element.attr("label")){ prev(evt.target).classList.remove('label_is_active'); } /* no val no placeholder? */ if(p!=""){ element.attr("placeholder", p); } /* no val and require */ if(element.attr('required')){ element.removeClass("success"); /* Remove success */ element.removeClass("warning"); /* Remove warning */ element.addClass('error'); next(evt.target).classList.add('error'); } else { /* no val and not require */ element.removeClass('error'); next(evt.target).classList.remove('error'); element.removeClass('success'); next(evt.target).classList.remove('success'); } element.removeClass("has_value"); } else { /* Remove Error */ element.removeClass('error'); next(evt.target).classList.remove('error'); /* Have value = Success*/ if(element.attr('required')){ element.addClass('success'); next(evt.target).classList.add('success'); } /* Have value = Success */ if(!element.hasClass("has_value")){ element.addClass("has_value"); } /* Have value but warrning */ if(element.attr("warning") && element.attr("warning") != 0){ if(element.val().length < parseInt(element.attr("warning"))){ element.removeClass('success'); element.addClass('warning'); return; } else{ element.removeClass('warning'); } } /* Have value & email & require */ if(element.attr('type') == 'email' && element.attr('required')){ if(!emailValidate(element.val())){ /* Invalid Format */ element.removeClass("success"); /* Remove success */ element.removeClass("warning"); /* Remove warning */ element.addClass("error"); next(evt.target).classList.add('error'); return; } else { /* Valid */ element.removeClass("error"); next(evt.target).classList.remove('error'); } } } }); }; return promise; }); _ui_share_app.directive('componentCurrencyPrice', function($rootScope, $routeParams) { var templateName = 'componentCurrencyPrice'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.link = function($scope, element, attr) { $scope.parentElement = element.parent(); $scope.checkPrice = function(price, callback) { var check_price = 0; if (price.includes(".")) { check_price = 2; } callback(check_price); }; $scope.formatMoney = function(amount, decimalCount = 2, decimal = ".", thousands = ",") { try { decimalCount = Math.abs(decimalCount); decimalCount = isNaN(decimalCount) ? 2 : decimalCount; const negativeSign = amount < 0 ? "-" : ""; let i = parseInt(amount = Math.abs(Number(amount) || 0).toFixed(decimalCount)).toString(); let j = (i.length > 3) ? i.length % 3 : 0; return negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands) + (decimalCount ? decimal + Math.abs(amount - i).toFixed(decimalCount).slice(2) : ""); } catch (e) { console.log('componentCurrencyPrice : e :', e); } }; $scope.buildPrice = function(data) { $scope.checkPrice(data.price, function(check_price) { element.addClass('force-dispaly-none'); $scope.parentElement.append($scope.formatMoney(' ' + data.price, check_price, ".", ",") + ' ' + data.currency); }); }; $scope.buildPrice(attr); } return promise; });_ui_share_app.factory('$componentData', function componentData($routeParams, $timeout) { return });_ui_share_app.directive('componentDataProduct', function($rootScope, $routeParams, $location) { var templateName = 'componentDataProduct'; var componentMain = 'componentData'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { shopname: '@shopname', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, loopApi: function(cur_page, total_rows, total_data_array) { var _self = this; if (total_rows > total_data_array) { _self.getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); $scope.getData().consoleLog("getData : getRouteParams : params : ", params); var loop_cur_page = cur_page + 1 var filter_json = {}; $scope.dataSet[0].dataSend = { 'cur_page': loop_cur_page, 'per_page': $scope.total.per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; $scope.getData().dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { var oldData = $scope.dataArray.data.dataList; $scope.dataArray.data.dataList = oldData.concat(output.data.dataList); $scope.total.total_data_array = $scope.total.total_data_array + output.data.dataList.length; $scope.dataArrayState = $scope.getData().stateData(false, true); if ($scope.total.total_data_array < output.data.total_rows) { _self.loopApi(loop_cur_page, output.data.total_rows, output.data.dataList.length); } }); }); }); } }, download: function() {}, more: function() { var _self = this; var cur_page = $scope.dataMore.cur_page - 1; $scope.dataMore.state = true; if ($scope.dataMore.cur_page <= $scope.total.dataArray.length) { $scope.dataMore.cur_page++; var oldData = $scope.dataArray.data.dataList; $scope.dataArray.data.dataList = oldData.concat($scope.total.dataArray[cur_page]); $scope.dataMore.state = false; if ($scope.dataArray.data.dataList.length < $scope.total.total_rows) { $scope.dataMore.show = true; } else { $scope.dataMore.show = false; } } else { setTimeout(function() { _self.more(); }, 1000); } }, main: function() { var _self = this; } } return getFunction; }; $scope.dataSet = [{ api: "product/lists", dataSend: {} }]; $scope.dataArray = []; $scope.dataArrayState = { load: false, done: false }; $scope.total = { cur_page: 1, per_page: 100, total_rows: 0, total_data_array: 0 }; $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); $scope.getData().consoleLog("getData : getRouteParams : params : ", params); var filter_json = {}; $scope.dataSet[0].dataSend = { 'cur_page': $scope.total.cur_page, 'per_page': $scope.total.per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; $scope.getData().dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { $scope.getData().consoleLog("getData : dataSend : api : ", api); $scope.getData().consoleLog("getData : dataSend : dataSend : ", dataSend); $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output; $scope.dataArrayState = $scope.getData().stateData(false, true); $scope.getData().consoleLog("getData : getApi : output : ", output); $scope.total.total_rows = output.data.total_rows; $scope.total.total_data_array = output.data.dataList.length; $scope.getData().loopApi($scope.total.cur_page, $scope.total.total_rows, $scope.total.total_data_array); }); }); }); }; return promise; });_ui_share_app.directive('componentDatetimePicker', function() { return { require: 'ngModel', link: function(scope, element, attr, ngModelCtrl) { $(element).datetimepicker({ locale: 'en', maxDate: new Date() }).on('dp.change', function(event) { scope.$apply(function() { ngModelCtrl.$setViewValue(event.date.format('DD-MM-YYYY HH:mm:ss')); }); }); } }; });_ui_share_app.factory('$componentDealCard', function componentDealCard($routeParams, $timeout) { return });_ui_share_app.directive('componentDealCardA', function($rootScope, $routeParams) { var templateName = 'componentDealCardA'; var componentMain = 'componentDealCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '=datain', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.timeRunStartEnd = function(timestampStart, timestampEnd) { var timeA = new Date(); var Year = parseInt($scope.momentJs.getYearString(timestampEnd)); var Month = parseInt($scope.momentJs.getMonthString(timestampEnd)); var Day = parseInt($scope.momentJs.getDayString(timestampEnd)); var Hours = parseInt($scope.momentJs.getHoursString(timestampEnd)); var Minutes = parseInt($scope.momentJs.getMinutesString(timestampEnd)); var Seconds = parseInt($scope.momentJs.getSecondsString(timestampEnd)); /*var timeB = Year + " : " + Month + " : " + Day + " : " + Hours + " : " + Minutes + " : " + Seconds; var timeB = new Date(2017, 10, 7, 13, 0, 0, 0); var timeDifference = -1;*/ var timeB = new Date(Year, Month - 1, Day, Hours, Minutes, Seconds, 0); var timeDifference = timeB.getTime() - timeA.getTime(); if (timeDifference >= 0) {     timeDifference = timeDifference / 1000;     timeDifference = Math.floor(timeDifference);     var wan = Math.floor(timeDifference / 86400);     var l_wan = timeDifference % 86400;     var hour = Math.floor(l_wan / 3600);     var l_hour = l_wan % 3600;     var minute = Math.floor(l_hour / 60);     var second = l_hour % 60;     var data =  wan + " วัน " + hour + " ช.ม "     + minute + " น. " + second + " ว.";         if (wan == 0 && hour == 0 && minute == 0 && second == 0) {             clearInterval(iCountDown);         } } return data; } $scope.timeStart = function(timestampStart, timestampEnd) { var dates = new Date().getTime(); var datesLen = dates.toString().length; var timeStart = timestampStart.toString(); var timeEnd = timestampEnd.toString(); var subdate = parseInt(dates.toString().substring(0, timeEnd.length)); var end = timestampEnd - subdate; return end; } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.dates = new Date(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.momentJs = { getDayString: function(timestamp) { return GAEAPI.time.dateFormat("DD", timestamp); }, getMonthString: function(timestamp) { return GAEAPI.time.dateFormat("MM", timestamp); }, getYearString: function(timestamp) { return GAEAPI.time.dateFormat("YYYY", timestamp); }, getHoursString: function(timestamp) { return GAEAPI.time.dateFormat("HH", timestamp); }, getMinutesString: function(timestamp) { return GAEAPI.time.dateFormat("mm", timestamp); }, getSecondsString: function(timestamp) { return GAEAPI.time.dateFormat("ss", timestamp); }, getTimesString: function(timestamp) { return GAEAPI.time.dateFormat("D : hh : mm : ss", timestamp); } }; }; return promise; });_ui_share_app.directive('componentDealCardB', function($rootScope, $routeParams, $location) { var templateName = 'componentDealCardB'; var componentMain = 'componentDealCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '=datain', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = "componentDealCardB"; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, id, title) { var _self = this; var titleurl = _self.titleUrl(title); $location.url(template + '/' + id + '-' + titleurl).replace(); } } return getFunction; }; $scope.getFunction().consoleLog("datashow : ", $scope.datashow); }; return promise; });_ui_share_app.directive('componentDealCardMain', function($rootScope, $routeParams) { var templateName = 'componentDealCardMain'; var componentMain = 'componentDealCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', dataout: '=datain', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });/*_ui_share_app.directive('componentFooter', function($rootScope, $routeParams) { var templateName = 'componentFooter'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id: '=', background: '@', primary: '@', secondary: '@', name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) {}; return promise; });*/ _ui_share_app.factory('$componentDealGroup', function componentDealGroup($routeParams, $timeout) { return });_ui_share_app.directive('componentDealGroupA', function($rootScope, $routeParams) { var templateName = 'componentDealGroupA'; var componentMain = 'componentDealGroup'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dealGroupLists = []; $scope.dealGroupState = { load: false, done: false }; $scope.getDealGroupLists = function() { $scope.dealGroupState = $scope.StateData(true, false); var dataSend = { cur_page: 1, per_page: 10 }; GAEAPI.get('deal_group/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope.dealGroupLists = output.data.dataList; } $scope.dealGroupState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getDealGroupLists(); $scope.lifetimeEndTime = []; $scope.dealGroupListsLoad = []; $scope.getDealGroupListsLoad = function() { var dataSend = { cur_page: 1, per_page: 10 }; GAEAPI.get('deal_group/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope.dealGroupListsLoad = output.data.dataList; } for (var i = 0; i < $scope.lifetimeEndTimeLengthLoad; i++) { $scope.lifetimeEndTimeE[i] = $scope.dealGroupListsLoad[i].product_lifetime.lifetime_end_time; if ($scope.lifetimeEndTimeS[i] != $scope.lifetimeEndTimeE[i]) { $scope.dealGroupLists = output.data.dataList; $scope.lifetimeEndTimeS = $scope.lifetimeEndTimeE; } } }); }; $scope.timeRunStartEnd = function(timestampStart, timestampEnd) { var timeA = new Date(); var Year = parseInt($scope.momentJs.getYearString(timestampEnd)); var Month = parseInt($scope.momentJs.getMonthString(timestampEnd)); var Day = parseInt($scope.momentJs.getDayString(timestampEnd)); var Hours = parseInt($scope.momentJs.getHoursString(timestampEnd)); var Minutes = parseInt($scope.momentJs.getMinutesString(timestampEnd)); var Seconds = parseInt($scope.momentJs.getSecondsString(timestampEnd)); /*var timeB = Year + " : " + Month + " : " + Day + " : " + Hours + " : " + Minutes + " : " + Seconds; var timeB = new Date(2017, 10, 7, 13, 0, 0, 0); var timeDifference = -1;*/ var timeB = new Date(Year, Month - 1, Day, Hours, Minutes, Seconds, 0); var timeDifference = timeB.getTime() - timeA.getTime(); if (timeDifference >= 0) {     timeDifference = timeDifference / 1000;     timeDifference = Math.floor(timeDifference);     var wan = Math.floor(timeDifference / 86400);     var l_wan = timeDifference % 86400;     var hour = Math.floor(l_wan / 3600);     var l_hour = l_wan % 3600;     var minute = Math.floor(l_hour / 60);     var second = l_hour % 60;     var data =   "เหลือเวลา " + wan + " วัน " + hour + " ชั่วโมง "     + minute + " นาที " + second + " วินาที";         if (wan == 0 && hour == 0 && minute == 0 && second == 0) {             clearInterval(iCountDown);         } } return data; } $scope.timeStart = function(timestampStart, timestampEnd) { var dates = new Date().getTime(); var datesLen = dates.toString().length; var timeStart = timestampStart.toString(); var timeEnd = timestampEnd.toString(); var subdate = parseInt(dates.toString().substring(0, timeEnd.length)); var end = timestampEnd - subdate; return end; } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.dates = new Date(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.momentJs = { getDayString: function(timestamp) { return GAEAPI.time.dateFormat("DD", timestamp); }, getMonthString: function(timestamp) { return GAEAPI.time.dateFormat("MM", timestamp); }, getYearString: function(timestamp) { return GAEAPI.time.dateFormat("YYYY", timestamp); }, getHoursString: function(timestamp) { return GAEAPI.time.dateFormat("HH", timestamp); }, getMinutesString: function(timestamp) { return GAEAPI.time.dateFormat("mm", timestamp); }, getSecondsString: function(timestamp) { return GAEAPI.time.dateFormat("ss", timestamp); }, getTimesString: function(timestamp) { return GAEAPI.time.dateFormat("D : hh : mm : ss", timestamp); } }; $scope.shopName = ''; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopName = e.data.shop_name; } }); }; $scope.getShopCurrent(); $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentDealGroupProductslideA', function($rootScope, $routeParams) { var componentMain = 'componentDealGroup'; var componentChild = 'productslideA'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', size: '@size', productid: '@productid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.slideProductDeal = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.productLists = []; $scope.productListsState = { load: false, done: false }; $scope.getProductLists = function() { $scope.productListsState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': $scope.productid, }; GAEAPI.get('deal_group/id', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope.productLists = output.data.product_set_array; } $scope.productListsState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getProductLists(); $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentDealListA', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentDealListA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', margin:'@margin', imgpath:'@imgpath', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 6; i++){ r.push({ banner_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/180x150.jpg'}], callback_array:true }); } return r; }; $scope.data = false; $scope.data_desktop = []; $scope.data_mobile = []; $scope._param = $routeParams.deal_id; console.log("eyreyhfdsf :", $scope._param); $scope.$watch('_param', function(newValue, oldValue) { if (newValue) { $scope.getData(newValue); } }); $scope.type = 'Deallist'; $scope.done = false; $scope.prev_win_size = $(window).width(); $scope.getData = function(item){ console.log("eyreyhfdsf : ",item); GAEAPI.get('deal_group/id', {'txt_product_id':item}, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data; $scope.data = resultArray; console.log("eyreyhfdsf : ",$scope.data); }); }; $scope.viewData = function(){ return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.viewLink = function(i){ $window.location.href=i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.timeRunStartEnd = function(timestampStart, timestampEnd) { var timeA = new Date(); var Year = parseInt($scope.momentJs.getYearString(timestampEnd)); var Month = parseInt($scope.momentJs.getMonthString(timestampEnd)); var Day = parseInt($scope.momentJs.getDayString(timestampEnd)); var Hours = parseInt($scope.momentJs.getHoursString(timestampEnd)); var Minutes = parseInt($scope.momentJs.getMinutesString(timestampEnd)); var Seconds = parseInt($scope.momentJs.getSecondsString(timestampEnd)); /*var timeB = Year + " : " + Month + " : " + Day + " : " + Hours + " : " + Minutes + " : " + Seconds; var timeB = new Date(2017, 10, 7, 13, 0, 0, 0); var timeDifference = -1;*/ var timeB = new Date(Year, Month - 1, Day, Hours, Minutes, Seconds, 0); var timeDifference = timeB.getTime() - timeA.getTime(); if (timeDifference >= 0) {     timeDifference = timeDifference / 1000;     timeDifference = Math.floor(timeDifference);     var wan = Math.floor(timeDifference / 86400);     var l_wan = timeDifference % 86400;     var hour = Math.floor(l_wan / 3600);     var l_hour = l_wan % 3600;     var minute = Math.floor(l_hour / 60);     var second = l_hour % 60;     var data =   wan + " วัน " + hour + " ชั่วโมง "     + minute + " นาที " + second + " วินาที";         if (wan == 0 && hour == 0 && minute == 0 && second == 0) {             clearInterval(iCountDown);         } } return data; }; $scope.timeStart = function(timestampStart, timestampEnd) { var dates = new Date().getTime(); var datesLen = dates.toString().length; if(timestampStart != undefined){ var timeStart = timestampStart.toString(); } if(timestampEnd != undefined){ var timeEnd = timestampEnd.toString(); } var subdate = parseInt(dates.toString().substring(0, timeEnd.length)); var end = timestampEnd - subdate; return end; } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.dates = new Date(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.momentJs = { getDayString: function(timestamp) { return GAEAPI.time.dateFormat("DD", timestamp); }, getMonthString: function(timestamp) { return GAEAPI.time.dateFormat("MM", timestamp); }, getYearString: function(timestamp) { return GAEAPI.time.dateFormat("YYYY", timestamp); }, getHoursString: function(timestamp) { return GAEAPI.time.dateFormat("HH", timestamp); }, getMinutesString: function(timestamp) { return GAEAPI.time.dateFormat("mm", timestamp); }, getSecondsString: function(timestamp) { return GAEAPI.time.dateFormat("ss", timestamp); }, getTimesString: function(timestamp) { return GAEAPI.time.dateFormat("D : hh : mm : ss", timestamp); } }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; }; return promise; }); _ui_share_app.factory('$componentDealProduct', function componentDealProduct($routeParams, $timeout) { return });_ui_share_app.directive('componentDealProductSlideTypeA', function($rootScope, $routeParams) { var templateName = 'componentDealProductSlideTypeA'; var componentMain = 'componentDealProduct'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', limitdata: '@limitdata', iconsize: '@iconsize', iconnext: '@iconnext', iconback: '@iconback', showresult: '@showresult', slidestoshowlarge: '@slidestoshowlarge', slidestoshowmedium: '@slidestoshowmedium', slidestoshowsmall: '@slidestoshowsmall', slidestoshowextrasmall: '@slidestoshowextrasmall', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope._showresult = (typeof $scope.showresult !== 'undefined' && typeof $scope.showresult !== '') ? $scope.showresult : true; $scope._iconsize = (typeof $scope.iconsize !== 'undefined' && typeof $scope.iconsize !== '') ? $scope.iconsize : 30; $scope._iconback = (typeof $scope.iconback !== 'undefined' && typeof $scope.iconback !== '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = (typeof $scope.iconnext !== 'undefined' && typeof $scope.iconnext !== '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope._slidestoshowlarge = parseInt((typeof $scope.slidestoshowlarge !== 'undefined' && typeof $scope.slidestoshowlarge !== '') ? $scope.slidestoshowlarge : 4); $scope._slidestoshowmedium = parseInt((typeof $scope.slidestoshowmedium !== 'undefined' && typeof $scope.slidestoshowmedium !== '') ? $scope.slidestoshowmedium : 3); $scope._slidestoshowsmall = parseInt((typeof $scope.slidestoshowsmall !== 'undefined' && typeof $scope.slidestoshowsmall !== '') ? $scope.slidestoshowsmall : 2); $scope._slidestoshowextrasmall = parseInt((typeof $scope.slidestoshowextrasmall !== 'undefined' && typeof $scope.slidestoshowextrasmall !== '') ? $scope.slidestoshowextrasmall : 1); $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "badge_id_array": [id] } var dataSend = { 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('deal/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; } setTimeout(function() { $scope._dataArrayState = $scope.StateData(false, true); }, 1000); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getProductArray($scope.badgeid); $scope.mkCarousel = function(elem) { $('.component-badge-slide-type-d').css('height', '0'); $('.component-badge-slide-type-d').css('opacity', '0'); console.log("mkCarousel : ", $scope._slidestoshowlarge, $scope._slidestoshowmedium, $scope._slidestoshowsmall, $scope._slidestoshowextrasmall); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: false, autoplay: true, autoplaySpeed: 4000, slidesToShow: $scope._slidestoshowlarge, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: $scope._slidestoshowmedium, } }, { breakpoint: 991, settings: { slidesToShow: $scope._slidestoshowsmall, } }, { breakpoint: 767, settings: { slidesToShow: $scope._slidestoshowextrasmall, } }] }).closest('section').addClass('active'); $('.component-badge-slide-type-d').css('height', 'auto'); $('.component-badge-slide-type-d').css('opacity', '1'); }, 1500); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; });_ui_share_app.directive('componentDealProductTypeA', function($rootScope, $routeParams) { var templateName = 'componentDealProductTypeA'; var componentMain = 'componentDealProduct'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { col: '@col', limitdata: '@limitdata', component: '@component', stylebutton: '@stylebutton', backgroundtopic: '@backgroundtopic', backgroundcard: '@backgroundcard', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', 'left': '?left', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { /* Images */ $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; /* Images */ $scope._component = (typeof $scope.component !== 'undefined') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_round_small'; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.viewRouteParams = function() { return $routeParams; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var json = { 'badge_id_array': [18] }; var dataSend = { cur_page: 1, per_page: $scope._limitdata, 'txt_filter_json': JSON.stringify(json) }; GAEAPI.get('deal/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); $scope.timeStart = function(timestampStart, timestampEnd) { var dates = new Date().getTime(); var datesLen = dates.toString().length; if (timestampStart != undefined && timestampEnd != undefined) { var timeStart = timestampStart.toString(); var timeEnd = timestampEnd.toString(); var subdate = parseInt(dates.toString().substring(0, timeEnd.length)); var end = timestampEnd - subdate; } else { end = 0; } return end; } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.dates = new Date(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); }; return promise; }); _ui_share_app.directive('componentDealSlide', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentDealSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', margin:'@margin', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 6; i++){ r.push({ banner_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/180x150.jpg'}], callback_array:true }); } return r; }; $scope.data = false; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'Dealslide'; $scope.done = false; $scope.prev_win_size = $(window).width(); GAEAPI.get('deal_group/id', {'txt_product_id':73893}, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data; $scope.data = resultArray; }); $scope.viewData = function(){ return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 4, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 1200, settings: { slidesToShow: 3, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ $window.location.href=i; }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if($('.component_carousel_map[data-id="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.initSlider(); }, 500); } }); $scope.checkHide = function(){ return ($('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length > 0) ? true : false; }; $scope.timeRunStartEnd = function(timestampStart, timestampEnd) { var timeA = new Date(); var Year = parseInt($scope.momentJs.getYearString(timestampEnd)); var Month = parseInt($scope.momentJs.getMonthString(timestampEnd)); var Day = parseInt($scope.momentJs.getDayString(timestampEnd)); var Hours = parseInt($scope.momentJs.getHoursString(timestampEnd)); var Minutes = parseInt($scope.momentJs.getMinutesString(timestampEnd)); var Seconds = parseInt($scope.momentJs.getSecondsString(timestampEnd)); /*var timeB = Year + " : " + Month + " : " + Day + " : " + Hours + " : " + Minutes + " : " + Seconds; var timeB = new Date(2017, 10, 7, 13, 0, 0, 0); var timeDifference = -1;*/ var timeB = new Date(Year, Month - 1, Day, Hours, Minutes, Seconds, 0); var timeDifference = timeB.getTime() - timeA.getTime(); if (timeDifference >= 0) {     timeDifference = timeDifference / 1000;     timeDifference = Math.floor(timeDifference);     var wan = Math.floor(timeDifference / 86400);     var l_wan = timeDifference % 86400;     var hour = Math.floor(l_wan / 3600);     var l_hour = l_wan % 3600;     var minute = Math.floor(l_hour / 60);     var second = l_hour % 60;     var data =   wan + " วัน " + hour + " ชั่วโมง "     + minute + " นาที " + second + " วินาที";         if (wan == 0 && hour == 0 && minute == 0 && second == 0) {             clearInterval(iCountDown);         } } return data; }; $scope.timeStart = function(timestampStart, timestampEnd) { var dates = new Date().getTime(); var datesLen = dates.toString().length; if(timestampStart != undefined){ var timeStart = timestampStart.toString(); } if(timestampEnd != undefined){ var timeEnd = timestampEnd.toString(); } if(timeEnd != undefined){ var subdate = parseInt(dates.toString().substring(0, timeEnd.length)); } var end = timestampEnd - subdate; return end; } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.dates = new Date(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.momentJs = { getDayString: function(timestamp) { return GAEAPI.time.dateFormat("DD", timestamp); }, getMonthString: function(timestamp) { return GAEAPI.time.dateFormat("MM", timestamp); }, getYearString: function(timestamp) { return GAEAPI.time.dateFormat("YYYY", timestamp); }, getHoursString: function(timestamp) { return GAEAPI.time.dateFormat("HH", timestamp); }, getMinutesString: function(timestamp) { return GAEAPI.time.dateFormat("mm", timestamp); }, getSecondsString: function(timestamp) { return GAEAPI.time.dateFormat("ss", timestamp); }, getTimesString: function(timestamp) { return GAEAPI.time.dateFormat("D : hh : mm : ss", timestamp); } }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; }; return promise; }); _ui_share_app.directive('componentDealsTypeA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentDealsTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'badgetext': '@badgetext', 'imgpath': '@imgpath', 'margin': '@margin', 'buttontext': '@buttontext' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval) { $scope.data = []; $scope.all_data = []; $scope.getData = function() { $scope.all_data = []; $scope.data = []; var j = { 'badge_id_array': [18] }; var d = { 'cur_page': 1, 'per_page': 12, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('deal/lists', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data = e.data.dataList; var date_now = new Date(); var date_dif_start = []; var date_dif_end = []; var time_year = []; var time_mount = []; var time_date = []; var time_hr = []; var time_mi = []; var time_se = []; var time_year_end = []; var time_mount_end = []; var time_date_end = []; var time_hr_end = []; var time_mi_end = []; var time_se_end = []; var timeDifference_start = []; var timeDifference_end = []; for (var i = 0; i < $scope.data.length; i++) { time_year[i] = GAEAPI.time.dateFormat("YYYY", $scope.data[i].product_lifetime.lifetime_start_time); time_mount[i] = GAEAPI.time.dateFormat("M", $scope.data[i].product_lifetime.lifetime_start_time); time_date[i] = GAEAPI.time.dateFormat("D", $scope.data[i].product_lifetime.lifetime_start_time); time_hr[i] = GAEAPI.time.dateFormat("H", $scope.data[i].product_lifetime.lifetime_start_time); time_mi[i] = GAEAPI.time.dateFormat("m", $scope.data[i].product_lifetime.lifetime_start_time); time_se[i] = GAEAPI.time.dateFormat("s", $scope.data[i].product_lifetime.lifetime_start_time); time_year_end[i] = GAEAPI.time.dateFormat("YYYY", $scope.data[i].product_lifetime.lifetime_end_time); time_mount_end[i] = GAEAPI.time.dateFormat("M", $scope.data[i].product_lifetime.lifetime_end_time); time_date_end[i] = GAEAPI.time.dateFormat("D", $scope.data[i].product_lifetime.lifetime_end_time); time_hr_end[i] = GAEAPI.time.dateFormat("H", $scope.data[i].product_lifetime.lifetime_end_time); time_mi_end[i] = GAEAPI.time.dateFormat("m", $scope.data[i].product_lifetime.lifetime_end_time); time_se_end[i] = GAEAPI.time.dateFormat("s", $scope.data[i].product_lifetime.lifetime_end_time); date_dif_start[i] = new Date(time_year[i], time_mount[i] - 1, time_date[i], time_hr[i], time_mi[i], time_se[i], 0); date_dif_end[i] = new Date(time_year_end[i], time_mount_end[i] - 1, time_date_end[i], time_hr_end[i], time_mi_end[i], time_se_end[i], 0); timeDifference_start[i] = date_now.getTime() - date_dif_start[i].getTime(); timeDifference_end[i] = date_dif_end[i].getTime() - date_now.getTime(); console.log("hr : mi : se =", time_hr_end[i], time_mi_end[i], time_se_end[i]); console.log("dealtestrew1 :", timeDifference_start[i]); console.log("hr : dealtestrew2 :", timeDifference_end[i]); if (timeDifference_start[i] > 0 && timeDifference_end[i] > 2000) { $scope.all_data.push($scope.data[i]); } } $scope.timeCountStart2($scope.all_data); console.log("dealsLists", $scope.all_data); } }); }; $scope.getData(); $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.momentJs = { getDayString: function(timestamp) { return GAEAPI.time.dateFormat("DD", timestamp); }, getMonthString: function(timestamp) { return GAEAPI.time.dateFormat("MMM", timestamp); }, getHoursString: function(timestamp) { return GAEAPI.time.dateFormat("hh", timestamp); }, getMinutesString: function(timestamp) { return GAEAPI.time.dateFormat("mm", timestamp); }, getSecondsString: function(timestamp) { return GAEAPI.time.dateFormat("ss", timestamp); }, getTimesString: function(timestamp) { return GAEAPI.time.dateFormat("DD : hh : mm : ss", timestamp); } }; var d_date = new Date(); var timeB = new Date('2017', '9', '21', '0', '0', '0', '0'); var timeDifference = timeB.getTime() - d_date.getTime(); $scope.counter = timeDifference; // console.log("time_current :", $scope.counter); $scope.timeCount = function() { var time = $scope.momentJs.getTimesString($scope.counter); return time; } $scope.timeout_promise = null; $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.counter--; $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.showPart = []; $scope.countDown = function(settime) { var dateTimeParts = []; var timeParts = []; var dateParts = []; var time_year = []; var time_mount = []; var time_date = []; var time_hr = []; var time_mi = []; var time_se = []; var timeA = []; var timeB = []; var timeC = []; var timeDifference = []; var timeDifference_temp = []; var wan = []; var l_wan = []; var hour = []; var l_hour = []; var minute = []; var second = []; for (var i = 0; i < settime.length; i++) { time_year[i] = GAEAPI.time.dateFormat("YYYY", settime[i].product_lifetime.lifetime_end_time); time_mount[i] = GAEAPI.time.dateFormat("M", settime[i].product_lifetime.lifetime_end_time); time_date[i] = GAEAPI.time.dateFormat("D", settime[i].product_lifetime.lifetime_end_time); time_hr[i] = GAEAPI.time.dateFormat("H", settime[i].product_lifetime.lifetime_end_time); time_mi[i] = GAEAPI.time.dateFormat("m", settime[i].product_lifetime.lifetime_end_time); time_se[i] = GAEAPI.time.dateFormat("s", settime[i].product_lifetime.lifetime_end_time); timeA[i] = new Date(); /* วันเวลาปัจจุบัน*/ timeB[i] = new Date(time_year[i], (time_mount[i] - 1), time_date[i], time_hr[i], time_mi[i], time_se[i], '0'); timeDifference[i] = timeB[i].getTime() - timeA[i].getTime(); // console.log("timeDifference", timeDifference[i]); if (timeDifference[i] >= 0) { timeDifference[i] = timeDifference[i] / 1000; timeDifference[i] = Math.floor(timeDifference[i]); wan[i] = Math.floor(timeDifference[i] / 86400); l_wan[i] = timeDifference[i] % 86400; hour[i] = Math.floor(l_wan[i] / 3600); l_hour[i] = l_wan[i] % 3600; minute[i] = Math.floor(l_hour[i] / 60); second[i] = l_hour[i] % 60; pad("3", 2); pad("3", 3); pad("3", 3); pad("3", 3); pad("3", 3); pad("3", 3); $scope.showPart[i] = wan[i] + " : " + pad(hour[i], 2) + " : " + pad(minute[i], 2) + " : " + pad(second[i], 2); if (wan[i] == 0 && hour[i] == 0 && minute[i] == 0 && second[i] == 0) { $scope.data = []; $scope.all_data = []; $scope.getData(); } // console.log("check_array", $scope.showPart[i]); } } }; $scope.timeout_promise2 = null; $scope.timeCountStart2 = function(settime) { $scope.timeout_promise2 = $timeout(function() { $scope.countDown(settime); $scope.timeCountStart2(settime); }, 1000); } function pad(str, max) { str = str.toString(); return str.length < max ? pad("0" + str, max) : str; } }; return promise; });_ui_share_app.directive('componentDealsTypeB', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentDealsTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'badgetext': '@badgetext', 'imgpath': '@imgpath', 'margin': '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval) { $scope.data = []; $scope.all_data = []; $scope.getData = function() { $scope.all_data = []; $scope.data = []; var j = { 'badge_id_array': [18] }; var d = { 'cur_page': 1, 'per_page': 10, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('deal/lists', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data = e.data.dataList; var date_now = new Date(); var date_dif_start = []; var date_dif_end = []; var time_year = []; var time_mount = []; var time_date = []; var time_hr = []; var time_mi = []; var time_se = []; var time_year_end = []; var time_mount_end = []; var time_date_end = []; var time_hr_end = []; var time_mi_end = []; var time_se_end = []; var timeDifference_start = []; var timeDifference_end = []; for (var i = 0; i < $scope.data.length; i++) { time_year[i] = GAEAPI.time.dateFormat("YYYY", $scope.data[i].product_lifetime.lifetime_start_time); time_mount[i] = GAEAPI.time.dateFormat("M", $scope.data[i].product_lifetime.lifetime_start_time); time_date[i] = GAEAPI.time.dateFormat("D", $scope.data[i].product_lifetime.lifetime_start_time); time_hr[i] = GAEAPI.time.dateFormat("H", $scope.data[i].product_lifetime.lifetime_start_time); time_mi[i] = GAEAPI.time.dateFormat("m", $scope.data[i].product_lifetime.lifetime_start_time); time_se[i] = GAEAPI.time.dateFormat("s", $scope.data[i].product_lifetime.lifetime_start_time); time_year_end[i] = GAEAPI.time.dateFormat("YYYY", $scope.data[i].product_lifetime.lifetime_end_time); time_mount_end[i] = GAEAPI.time.dateFormat("M", $scope.data[i].product_lifetime.lifetime_end_time); time_date_end[i] = GAEAPI.time.dateFormat("D", $scope.data[i].product_lifetime.lifetime_end_time); time_hr_end[i] = GAEAPI.time.dateFormat("H", $scope.data[i].product_lifetime.lifetime_end_time); time_mi_end[i] = GAEAPI.time.dateFormat("m", $scope.data[i].product_lifetime.lifetime_end_time); time_se_end[i] = GAEAPI.time.dateFormat("s", $scope.data[i].product_lifetime.lifetime_end_time); date_dif_start[i] = new Date(time_year[i], time_mount[i] - 1, time_date[i], time_hr[i], time_mi[i], time_se[i], 0); date_dif_end[i] = new Date(time_year_end[i], time_mount_end[i] - 1, time_date_end[i], time_hr_end[i], time_mi_end[i], time_se_end[i], 0); timeDifference_start[i] = date_now.getTime() - date_dif_start[i].getTime(); timeDifference_end[i] = date_dif_end[i].getTime() - date_now.getTime(); console.log("hr : mi : se =", time_hr_end[i], time_mi_end[i], time_se_end[i]); console.log("dealtestrew1 :", timeDifference_start[i]); console.log("hr : dealtestrew2 :", timeDifference_end[i]); if (timeDifference_start[i] > 0 && timeDifference_end[i] > 2000) { $scope.all_data.push($scope.data[i]); } } $scope.timeCountStart2($scope.all_data); console.log("dealsLists", $scope.all_data); } }); }; $scope.getData(); $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.momentJs = { getDayString: function(timestamp) { return GAEAPI.time.dateFormat("DD", timestamp); }, getMonthString: function(timestamp) { return GAEAPI.time.dateFormat("MMM", timestamp); }, getHoursString: function(timestamp) { return GAEAPI.time.dateFormat("hh", timestamp); }, getMinutesString: function(timestamp) { return GAEAPI.time.dateFormat("mm", timestamp); }, getSecondsString: function(timestamp) { return GAEAPI.time.dateFormat("ss", timestamp); }, getTimesString: function(timestamp) { return GAEAPI.time.dateFormat("DD : hh : mm : ss", timestamp); } }; var d_date = new Date(); var timeB = new Date('2017', '9', '21', '0', '0', '0', '0'); var timeDifference = timeB.getTime() - d_date.getTime(); $scope.counter = timeDifference; console.log("time_current :", $scope.counter); $scope.timeCount = function() { var time = $scope.momentJs.getTimesString($scope.counter); return time; } $scope.timeout_promise = null; $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.counter--; $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.showPart = []; $scope.countDown = function(settime) { var dateTimeParts = []; var timeParts = []; var dateParts = []; var time_year = []; var time_mount = []; var time_date = []; var time_hr = []; var time_mi = []; var time_se = []; var timeA = []; var timeB = []; var timeC = []; var timeDifference = []; var timeDifference_temp = []; var wan = []; var l_wan = []; var hour = []; var l_hour = []; var minute = []; var second = []; for (var i = 0; i < settime.length; i++) { time_year[i] = GAEAPI.time.dateFormat("YYYY", settime[i].product_lifetime.lifetime_end_time); time_mount[i] = GAEAPI.time.dateFormat("M", settime[i].product_lifetime.lifetime_end_time); time_date[i] = GAEAPI.time.dateFormat("D", settime[i].product_lifetime.lifetime_end_time); time_hr[i] = GAEAPI.time.dateFormat("H", settime[i].product_lifetime.lifetime_end_time); time_mi[i] = GAEAPI.time.dateFormat("m", settime[i].product_lifetime.lifetime_end_time); time_se[i] = GAEAPI.time.dateFormat("s", settime[i].product_lifetime.lifetime_end_time); timeA[i] = new Date(); /* วันเวลาปัจจุบัน */ timeB[i] = new Date(time_year[i], (time_mount[i] - 1), time_date[i], time_hr[i], time_mi[i], time_se[i], '0'); timeDifference[i] = timeB[i].getTime() - timeA[i].getTime(); console.log("timeDifference", timeDifference[i]); if (timeDifference[i] >= 0) { timeDifference[i] = timeDifference[i] / 1000; timeDifference[i] = Math.floor(timeDifference[i]); wan[i] = Math.floor(timeDifference[i] / 86400); l_wan[i] = timeDifference[i] % 86400; hour[i] = Math.floor(l_wan[i] / 3600); l_hour[i] = l_wan[i] % 3600; minute[i] = Math.floor(l_hour[i] / 60); second[i] = l_hour[i] % 60; pad("3", 2); pad("3", 3); pad("3", 3); pad("3", 3); pad("3", 3); pad("3", 3); $scope.showPart[i] = wan[i] + " : " + pad(hour[i], 2) + " : " + pad(minute[i], 2) + " : " + pad(second[i], 2); if (wan[i] == 0 && hour[i] == 0 && minute[i] == 0 && second[i] == 0) { $scope.data = []; $scope.all_data = []; $scope.getData(); } console.log("check_array", $scope.showPart[i]); } } }; $scope.timeout_promise2 = null; $scope.timeCountStart2 = function(settime) { $scope.timeout_promise2 = $timeout(function() { $scope.countDown(settime); $scope.timeCountStart2(settime); }, 1000); } function pad(str, max) { str = str.toString(); return str.length < max ? pad("0" + str, max) : str; } }; return promise; });_ui_share_app.factory('$componentDiscount', function componentDiscount($routeParams, $timeout) { return });_ui_share_app.directive('componentDiscountProductTypeA', function($rootScope, $routeParams) { var templateName = 'componentDiscountProductTypeA'; var componentMain = 'componentDiscount'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', component: '@component', sizedata: '@sizedata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = { 'is_promotion_array': [1] }; var dataSend = { 'cur_page': 1, 'per_page': parseInt($scope.sizedata), 'txt_sortby': 'product_lastest_create', /*'txt_filter_json': JSON.stringify(txt_filter_json)*/ }; GAEAPI.get('product/lists', dataSend).then(function(res) { if (res.ok === 1) { /*$scope._dataArray = res.data.dataList;*/ for (var i = 0; i < res.data.dataList.length; i++) { if (res.data.dataList[i].product_discount != '') { if (res.data.dataList[i].product_discount.discount_name == '70%') { $scope._dataArray.push(res.data.dataList[i]); } } } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; }); _ui_share_app.directive('componentDivSample', function ($rootScope, $routeParams) { var templateName = 'componentDivSample'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'type':'@type', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; }; return promise; }); _ui_share_app.directive('componentEventDetailA', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentEventDetailA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', imagetop: '@imagetop', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataArray = false; $scope.getData = function(eventid){ // console.log("eyreyhfdsf 1:", video_id); $scope.dataArray = false; var d = { 'txt_event_id': eventid, }; GAEAPI.get('events/id',d,$scope).then(function(e){ if(e.ok == 1){ $scope.dataArray = e.data; console.log("eyreyhfdsf :", $scope.dataArray); setTimeout(function() { var rew = $('.get_height').height(); $('#setbackground').height(rew - 300); }, 1000); } }); }; $scope.getData($scope._idUrl($scope._viewRouteParams().event_id)); function addZero(i) { if (i < 10) { i = "0" + i; } return i; } function get_date_now() { var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var day_name_shot = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Fri", "Sat"]; $('#dashboard_date_now').text(day_name_shot[date_now.getDay()] + " " + date_now.getDate() + " " + month_names[date_now.getMonth()] + " " + date_now.getFullYear()); } $scope.getdatetime = function(time){ var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var day_name_shot = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Fri", "Sat"]; var datetime = new Date(parseInt(time)); var day = datetime.getDay(); var date = datetime.getDate(); var fullyear = datetime.getFullYear(); var month = datetime.getMonth(); var h = addZero(datetime.getHours()); var m = addZero(datetime.getMinutes()); var s = addZero(datetime.getSeconds()); var string = []; string[0] = day_name_shot[day] + ", " + month_names[month] + " " + date + " " + fullyear; string[1] = h+":"+m; return string; } }; return promise; }); _ui_share_app.directive('componentEventDetailB', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentEventDetailB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', imagetop: '@imagetop', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataArray = false; $scope.getData = function(eventid){ // console.log("eyreyhfdsf 1:", video_id); $scope.dataArray = false; var d = { 'txt_event_id': eventid, }; GAEAPI.get('events/id',d,$scope).then(function(e){ if(e.ok == 1){ $scope.dataArray = e.data; console.log("eyreyhfdsf :", $scope.dataArray); setTimeout(function() { var rew = $('.get_height').height(); $('#setbackground').height(rew - 300); }, 1000); } }); }; $scope.getData($scope._idUrl($scope._viewRouteParams().event_id)); function addZero(i) { if (i < 10) { i = "0" + i; } return i; } function get_date_now() { var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var day_name_shot = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Fri", "Sat"]; $('#dashboard_date_now').text(day_name_shot[date_now.getDay()] + " " + date_now.getDate() + " " + month_names[date_now.getMonth()] + " " + date_now.getFullYear()); } $scope.getdatetime = function(time){ var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var day_name_shot = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Fri", "Sat"]; var datetime = new Date(parseInt(time)); var day = datetime.getDay(); var date = datetime.getDate(); var fullyear = datetime.getFullYear(); var month = datetime.getMonth(); var h = addZero(datetime.getHours()); var m = addZero(datetime.getMinutes()); var s = addZero(datetime.getSeconds()); var string = []; string[0] = day_name_shot[day] + ", " + month_names[month] + " " + date + " " + fullyear; string[1] = h+":"+m; return string; } }; return promise; }); _ui_share_app.directive('componentEventListsA', function ($rootScope, $routeParams,$location, sliderProvider) { var templateName = 'componentEventListsA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; var GET_CACHE_STORE = function(pathName){ var prefixHost = "gae." + window.location.host; var suffixHost = prefixHost + "/" + pathName; var requestExecute = store.get(suffixHost); if(requestExecute == undefined || typeof requestExecute === 'undefined' || requestExecute == null){ return false; } else { return requestExecute; } }; var SAVE_CACHE_STORE = function(pathName, saveData){ var prefixHost = "gae." + window.location.host; var suffixHost = prefixHost + "/" + pathName; store.set(suffixHost, saveData); return GET_CACHE_STORE(pathName); }; // user location permission $scope.userLocationObj = false; $scope.REQUEST_USER_LOCATION_PERMISSION = function (callback) { var optionsForLocation = { enableHighAccuracy: ($(window).width() <= 991) ? true : false, maximumAge: 0, /* 10 Minute (1000 * 60) * 10 */ timeout: 5000, }; function success(pos) { var locationObj = { lat: pos.coords.latitude, lng: pos.coords.longitude }; $scope.userLocationObj = locationObj; SAVE_CACHE_STORE("component.componentEventListsA",locationObj); console.log(`REQUEST_USER_LOCATION_PERMISSION: ok : pos`, $scope.userLocationObj); callback(); } function error(err) { console.log(`REQUEST_USER_LOCATION_PERMISSION: err `, err); var cacheLocation = GET_CACHE_STORE("component.componentEventListsA"); if(cacheLocation){ $scope.userLocationObj = cacheLocation; console.log(`REQUEST_USER_LOCATION_PERMISSION: err => cache`, cacheLocation); } else { var defaultError = { lat: 13.692197, lng: 100.542791 }; $scope.userLocationObj = defaultError; } callback(); } navigator.geolocation.getCurrentPosition(success, error, optionsForLocation); }; var _googleMapInstance; var _googleMapInstanceMarkers = []; $scope.locationData_ = false; var googleMapHomeInit = function (location_array) { console.log("location lat long :",location_array); /* Query By Google distance */ /* https://maps.googleapis.com/maps/api/distancematrix/json?language=th&units=metric&origins=13.885988999999999,100.5172544&destinations=13.6696767,100.637485|13.6431183,100.5944557|13.659075,100.453442 */ /* Declare Main Map */ var center_default = { lat: 13.692197, lng: 100.542791 }; if($scope.userLocationObj){ center_default = $scope.userLocationObj; } /* Add Map */ _googleMapInstance = new google.maps.Map(document.getElementById('map2'), { center: center_default, mapTypeId: google.maps.MapTypeId.ROADMAP, zoom: 10, scrollwheel: false, draggable: true, }); if ($scope.userLocationObj) { var useObj = { lat: center_default.lat, lng: center_default.lng, title: 'ตำแหน่งของคุณ', }; location_array.push(useObj); } /* Map Location Array to Google's Map */ var locations = location_array; console.log("Map Product Dealer: Array", locations); var markers = locations.map(function (location, i) { /* Add Marker to map */ var marker = new google.maps.Marker({ position: { lat: location.lat, lng: location.lng }, icon: 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/Map_pin_icon.svg/15px-Map_pin_icon.svg.png', map: _googleMapInstance, title: location.title, infoWindow: '' }); console.log("Map Product Dealer: Item", location); console.log("marker detail :",marker); marker.infoWindow = '
' + "" + '

'; if (i > 0) { marker.infoWindow += 'ดูใน Google Map'; } marker.infoWindow += '
'; _googleMapInstanceMarkers[i] = marker; var infowindow = new google.maps.InfoWindow(); _googleMapInstanceInfoWindows = infowindow; google.maps.event.addListener(marker, 'click', (function (marker, content, infowindow) { return function () { infowindow.setContent(content); infowindow.open(_googleMapInstance, marker); }; })(marker, marker.infoWindow, infowindow)); $('[data-lat="' + location.lat + '"]').on('click', function () { _googleMapInstance.setCenter(new google.maps.LatLng(location.lat, location.lng)); _googleMapInstanceInfoWindows.setContent(marker.infoWindow); _googleMapInstanceInfoWindows.open(_googleMapInstance, marker); }); //console.log("Map Product Dealer: Item :", i, location); }); /* Add Circle Radius to map */ if ($scope.userLocationObj) { var meter = 1000; var circleUserArea = new google.maps.Circle({ strokeColor: '#FDD511', strokeOpacity: 0, strokeWeight: 2, fillColor: '#FDD511', fillOpacity: 0.15, map: _googleMapInstance, center: center_default, radius: (20 * meter) }); console.log("Map Product Dealer: Circle: Ok"); } else { console.log("Map Product Dealer: Circle: Not Ok"); } }; $scope.state = false; $scope.dataArray = []; $scope.time_more = 7; $scope.all_page = true; $scope.loadMore_is_load = true; $scope.myDate = false; $scope.plusSeven = false; $scope.getData = function(){ if($scope.dataArray.length){ $scope.time_more = $scope.time_more + 7; $scope.myDate = $scope.plusSeven; $scope.plusSeven = new Date($scope.myDate.setDate($scope.myDate.getDate() + $scope.time_more)); }else{ $scope.myDate = new Date(); $scope.plusSeven = new Date($scope.myDate.setDate($scope.myDate.getDate() + $scope.time_more)); } var buildLocationArray = []; /*var json_filter = { display_duration_from_to_range: [$scope.myDate.getTime(),$scope.plusSeven.getTime()] }*/ var json_filter = { event_display_duration_on_today: 1 } if (typeof $routeParams.tag !== 'undefined' && $routeParams.tag != '') { json_filter.tag_array_or = [$routeParams.tag]; } var d = { 'cur_page': 1, 'per_page': 100, 'txt_sort_by': 'display_duration_from_asc', 'txt_filter_json': JSON.stringify(json_filter) }; console.log("data list d :",d); GAEAPI.get('events/lists',d,$scope).then(function(e){ console.log("data list event :",e.data); if(e.ok == 1){ if ($scope.dataArray.length) { var curData = $scope.dataArray; $scope.dataArray = curData.concat(e.data.list); if (e.data.total_rows <= $scope.dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.dataArray = e.data.list; // alert($scope.dataArray.length); if (e.data.total_rows <= $scope.dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } // $scope.dataArray_done = true; console.log("Zoom: getDataProduct: e , new data", e); } $scope.REQUEST_USER_LOCATION_PERMISSION(function(){ // $scope.taglist = []; for (var i = 0; i < $scope.dataArray.length; i++) { if ($scope.dataArray[i].place_latitude != 0 && $scope.dataArray[i].place_longitude != 0) { buildLocationArray.push({ lat: parseFloat($scope.dataArray[i].place_latitude), lng: parseFloat($scope.dataArray[i].place_longitude), title: $scope.dataArray[i].place_title, }); } } if (buildLocationArray.length) { $scope.MapLists = buildLocationArray; /*googleDistance(buildLocationArray); */ /*var maphometimer = setTimeout(function () { googleMapHomeInit($scope.dealerLists); clearTimeout(maphometimer); }, 3000);*/ var timerProductWithOrigins = setInterval(function () { if ($("#map2").html() != "") { clearInterval(timerProductWithOrigins); googleMapHomeInit($scope.MapLists); } }, 1000); } }); $scope.loadMore_is_load = false; // $scope.dataArray = e.data.list; $scope.state = true; // console.log("eyreyhfdsf :", $scope.dataArray); } }); }; $scope.loadMore= function(){ $scope.loadMore_is_load = true; $timeout(function() { $scope.getData(); }, 300); }; $scope.getData(); $scope.taglist = function(tagname){ var taglist = []; if(tagname != ""){ taglist = tagname.split(","); } return taglist; }; function addZero(i) { if (i < 10) { i = "0" + i; } return i; }; $scope.getdatetime = function(time){ var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var day_name_shot = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Fri", "Sat"]; var datetime = new Date(parseInt(time)); var day = datetime.getDay(); var date = datetime.getDate(); var fullyear = datetime.getFullYear(); var month = datetime.getMonth(); var h = addZero(datetime.getHours()); var m = addZero(datetime.getMinutes()); var s = addZero(datetime.getSeconds()); // var string = []; // string[0] = day_name_shot[day] + ", " + month_names[month] + " " + date + " " + fullyear; // string[1] = h+":"+m; return day_name_shot[day] + ", " + month_names[month] + " " + date + " " + h+":"+m; }; }; return promise; }); _ui_share_app.directive('componentEventListsB', function($rootScope, $routeParams, $location, sliderProvider) { var templateName = 'componentEventListsB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.locationUrlReplace = function(id) { if (id != "") { var strHref = 'event-detail/'; strHref += id; $location.url(strHref).replace(); } }; $scope.state = false; $scope.dataArray = []; $scope.time_more = 7; $scope.all_page = false; $scope.loadMore_is_load = true; $scope.myDate = false; $scope.plusSeven = false; $scope.getData = function() { if ($scope.dataArray.length) { $scope.time_more = $scope.time_more + 7; $scope.myDate = $scope.plusSeven; $scope.plusSeven = new Date($scope.myDate.setDate($scope.myDate.getDate() + $scope.time_more)); } else { $scope.myDate = new Date(); $scope.plusSeven = new Date($scope.myDate.setDate($scope.myDate.getDate() + $scope.time_more)); } var buildLocationArray = []; /*var json_filter = { display_duration_from_to_range: [$scope.myDate.getTime(),$scope.plusSeven.getTime()] }*/ var json_filter = { event_display_duration_on_today: 1 } if (typeof $routeParams.tag !== 'undefined' && $routeParams.tag != '') { json_filter.tag_array_or = [$routeParams.tag]; } var d = { 'cur_page': 1, 'per_page': 100, 'txt_sort_by': 'display_duration_from_asc', 'txt_filter_json': JSON.stringify(json_filter) }; console.log("data list d :", d); GAEAPI.get('events/lists', d, $scope).then(function(e) { console.log("data list event :", e.data); if (e.ok == 1) { if ($scope.dataArray.length) { var curData = $scope.dataArray; $scope.dataArray = curData.concat(e.data.list); if (e.data.total_rows <= $scope.dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.dataArray = e.data.list; // alert($scope.dataArray.length); if (e.data.total_rows <= $scope.dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } // $scope.dataArray_done = true; console.log("Zoom: getDataProduct: e , new data", e); } $scope.loadMore_is_load = false; // $scope.dataArray = e.data.list; $scope.state = true; // console.log("eyreyhfdsf :", $scope.dataArray); } }); }; $scope.loadMore = function() { $scope.loadMore_is_load = true; $timeout(function() { $scope.getData(); }, 300); }; $scope.getData(); $scope.taglist = function(tagname) { var taglist = []; if (tagname != "") { taglist = tagname.split(","); } return taglist; }; function addZero(i) { if (i < 10) { i = "0" + i; } return i; }; $scope.getdatetime = function(time) { var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var day_name_shot = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Fri", "Sat"]; var datetime = new Date(parseInt(time)); var day = datetime.getDay(); var date = datetime.getDate(); var fullyear = datetime.getFullYear(); var month = datetime.getMonth(); var h = addZero(datetime.getHours()); var m = addZero(datetime.getMinutes()); var s = addZero(datetime.getSeconds()); // var string = []; // string[0] = day_name_shot[day] + ", " + month_names[month] + " " + date + " " + fullyear; // string[1] = h+":"+m; return day_name_shot[day] + ", " + month_names[month] + " " + date + " " + h + ":" + m; }; }; return promise; });/*_ui_share_app.directive('componentFooter', function($rootScope, $routeParams) { var templateName = 'componentFooter'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id: '=', background: '@', primary: '@', secondary: '@', name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) {}; return promise; });*/ _ui_share_app.factory('$componentFaq', function componentFooter($routeParams, $timeout) { return });_ui_share_app.directive('componentFaqA', function($rootScope, $routeParams) { var templateName = 'componentFaqA'; var componentMain = 'componentFaq'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.dataFaq = []; $scope.dataFaqLength = null; $scope.GetFaq = function() { var d = { 'cur_page': 1, 'per_page': 50 }; GAEAPI.get('faq/lists', d, $scope).then(function(e) { if (e.ok === 1) { $scope.dataFaq = e.data.dataList; $scope.dataFaqLength = Math.ceil($scope.dataFaq.length / 2); } console.log("dataFaq :", $scope.dataFaq); }); }; $scope.GetFaq(); $scope.controlPopupStatus = function(id) { if ($('#id'+id).css("display") !== 'inline') { return true; }else{ return false; } } $scope.control_popup = function(id) { var status = $scope.controlPopupStatus(id); console.log("componentFaqA ","ID : ",id," Status : ",status); console.log("componentFaqA ","ID : ",id," Status : ",$('#id'+id).css("display")); if (status == true) { document.getElementById('id'+id).style.display = 'inline'; } else { document.getElementById('id'+id).style.display = 'none'; } } $scope.control_popup_Status = function(id) { if ($('#id'+id).css("display") !== 'inline') { return 0; }else{ return 1; } } $scope.showDebug = function() { return (typeof $routeParams.debugfaq !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentFaqB', function($rootScope, $routeParams) { var templateName = 'componentFaqB'; var componentMain = 'componentFaq'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, imageUrl: function(size, image_url) { var url = image_url.split("/"), length_url = url[url.length - 1]; url[url.length - 1] = size + '_' + length_url; return url.join("/"); }, resizeImageUrl: function(output, callback) { var _self = this; for (var i = 0; i <= output.length; i++) { if (i < output.length) { if (output[i].faq_image.length != 0) { output[i].faq_image[0].image_url = _self.imageUrl('t100', output[i].faq_image[0].image_url); } } else { callback(output); } } }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.getData().main(); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.dataArrayLength = 0; $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); var dataSend = { 'cur_page': 1, 'per_page': 50 }; $scope.getData().dataSend('faq/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.getData().resizeImageUrl(output.data.dataList, function(dataList) { $scope.dataArray = dataList; $scope.dataArrayLength = Math.ceil(dataList.length / 2); $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); }); $scope.control_popup = function(id) { console.log("display:", document.getElementById(id).style.display); if (document.getElementById(id).style.display == '' || document.getElementById(id).style.display == 'none') { document.getElementById(id).style.display = 'initial'; document.getElementById('down' + id).style.display = 'none'; document.getElementById('up' + id).style.display = 'initial'; } else { document.getElementById(id).style.display = 'none'; document.getElementById('down' + id).style.display = 'initial'; document.getElementById('up' + id).style.display = 'none'; } } $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; }; return promise; });_ui_share_app.directive('componentFaqC', function($rootScope, $routeParams) { var templateName = 'componentFaqC'; var componentMain = 'componentFaq'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, imageUrl: function(size, image_url) { var url = image_url.split("/"), length_url = url[url.length - 1]; url[url.length - 1] = size + '_' + length_url; return url.join("/"); }, resizeImageUrl: function(output, callback) { var _self = this; for (var i = 0; i <= output.length; i++) { if (i < output.length) { if (output[i].faq_image.length != 0) { output[i].faq_image[0].image_url = _self.imageUrl('t100', output[i].faq_image[0].image_url); } } else { callback(output); } } }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.getData().main(); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.dataArrayLength = 0; $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); var dataSend = { 'cur_page': 1, 'per_page': 50 }; $scope.getData().dataSend('faq/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.getData().resizeImageUrl(output.data.dataList, function(dataList) { $scope.dataArray = dataList; $scope.dataArrayLength = Math.ceil(dataList.length / 2); $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); }); $scope.control_popup = function(id) { console.log("display:", document.getElementById(id).style.display); if (document.getElementById(id).style.display == '' || document.getElementById(id).style.display == 'none') { document.getElementById(id).style.display = 'initial'; document.getElementById('down' + id).style.display = 'none'; document.getElementById('up' + id).style.display = 'initial'; } else { document.getElementById(id).style.display = 'none'; document.getElementById('down' + id).style.display = 'initial'; document.getElementById('up' + id).style.display = 'none'; } } $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; }; return promise; });_ui_share_app.directive('componentFaqSlideTypeA', function($rootScope, $routeParams) { var templateName = 'componentFaqSlideTypeA'; var componentMain = 'componentFaq'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.dataFaqLists = []; $scope.dataFaqListsState = { load: true, done: false }; $scope.gaeFaqLists = function(callback) { $scope.dataFaqListsState = $scope.StateData(true, false); var faqLists = []; var dataSend = { 'cur_page': 1, 'per_page': 50 }; console.log("gaeFaqLists : dataSend : ", dataSend); GAEAPI.get('faq/lists', dataSend, $scope).then(function(output) { console.log("gaeFaqLists : output : ", output); if (output.ok == 1) { faqLists = output.data.dataList; callback(faqLists); } else { callback(faqLists); } }); }; $scope.gaeFaqLists(function(faqLists) { console.log("gaeFaqLists : faqLists : ", faqLists); $scope.dataFaqLists = faqLists; $scope.dataFaqListsState = $scope.StateData(false, true); }); $scope.dataKey = ''; $scope.dataId = function() { if ($scope.dataKey == '') { $scope.dataKey = Math.floor((Math.random() * 9999) + 1000); return $scope.dataKey; } else { return $scope.dataKey; } }; $scope.carousel = function(class_in, elem_in) { console.log("carousel : class_in : ", class_in); console.log("carousel : elem_in : ", elem_in); $(class_in).css('height', '0'); $(class_in).css('opacity', '0'); setTimeout(function() { var carousel = $(elem_in + '[data-id=' + $scope.dataId() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: false, autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { slidesToShow: 1, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); $(class_in).css('height', 'auto'); $(class_in).css('opacity', '1'); }, 100); }; }; return promise; });_ui_share_app.directive('componentFeatureCategoryProduct', function($rootScope, $routeParams) { var templateName = 'componentFeatureCategoryProduct'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referralid: '@referralid', size: '@size', sizelist: '@sizelist', sort: '@sort', col: '@col', component: '@component', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.size = (typeof $scope.size !== 'undefined') ? $scope.size : 8; $scope.sizelist = (typeof $scope.sizelist !== 'undefined') ? $scope.sizelist : 4; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._custom_ref = function () { $scope._dataArray = []; var txt_filter_json2 = { 'badge_id_array': [16] }; var dataSend = { 'txt_referral_type_id': 11, 'cur_page' : 1, 'per_page' : 50, 'txt_sortby': 'referral_oldest_create', 'txt_filter_json': JSON.stringify(txt_filter_json2) }; GAEAPI.get('referral/lists', dataSend).then(function (res) { if (res.ok === 1) { $scope._dataArray = (res.ok == 1) ? res.data.dataList : []; var temp_ttc = []; for (var i = 0; i < res.data.length; i++) { temp_ttc.push(res.data[i].referral_id); } ref_productArray = res.data.dataList; getproductForRef(0, function () { console.log("getproductForRef : thaiten: ", ref_productArray); }); } }); }; var ref_productArray = []; function getproductForRef(index, callback) { if (ref_productArray.length <= index) { if (callback) { callback(); } return; } var catData = ref_productArray[index]; var cat_refId = catData.referral_id; var txt_filter_json = { 'referral_id_array': [cat_refId], 'badge_id_array': [16] }; var dataSend = { 'cur_page': 1, 'per_page': 10, 'txt_sortby': 'product_oldest_create', 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend).then(function(res) { if (res.ok === 1) { catData.product_array = res.data.dataList; } $scope._dataArray = ref_productArray; getproductForRef((index + 1), callback); }); } $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._custom_ref(); $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.factory('$componentFlashSale', function componentFlashSale($routeParams, $timeout) { return });_ui_share_app.directive('componentFlashSaleIdProductTypeA', function($rootScope, $routeParams, $location) { var templateName = 'componentFlashSaleIdProductTypeA'; var componentMain = 'componentFlashSale'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', dealgroupid: '=dealgroupid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', 'topic_more': '?topicMore', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.component = "componentFlashSaleIdProductTypeA : "; /* api : 'deal_group/lists' txt_sortby : { 'product_lastest_create' , 'product_oldest_create' , 'product_title_a-z' , 'product_title_z-a' , 'root_category_index_asc' , 'root_category_index_desc' , } */ $scope.countdown = {}; $scope.dataSet = [{ api: "deal_group/id", dataSend: {}, dataArray: [], dataSendState: { load: false, done: false } }]; $scope.timeFunctiond = function() { var timeFunctiond = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { /* console.log(component, name, data); */ }); }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, momentUnix: function(callback) { var now = moment().unix(); callback(now); }, countdown: function(number, countdown, callback) { var _self = this; var timeCountdown = countdown.end - countdown.now; var duration = moment.duration(timeCountdown * 1000, "milliseconds"); if (timeCountdown > 0) { callback(number, duration, true); } else { callback(number, duration, false); } }, countdownArray: function(now, countdown, callback) { var _self = this; if (countdown.length != 0) { countdown.now = now; _self.countdown(0, countdown, function(number, duration, show) { countdown.day = (duration.days() <= 9) ? '0' + duration.days() : duration.days(); countdown.month = (duration.months() <= 9) ? '0' + duration.months() : duration.months(); countdown.year = (duration.years() <= 9) ? '0' + duration.years() : duration.years(); countdown.hours = (duration.hours() <= 9) ? '0' + duration.hours() : duration.hours(); countdown.minutes = (duration.minutes() <= 9) ? '0' + duration.minutes() : duration.minutes(); countdown.seconds = (duration.seconds() <= 9) ? '0' + duration.seconds() : duration.seconds(); countdown.show = show; }); callback(countdown); } else { callback(countdown); } }, loopTime: function() { var _self = this; var timeout_promise = $timeout(function() { _self.momentUnix(function(now) { _self.countdownArray(now, $scope.countdown, function(countdownArray) { if (!countdownArray.show) { _self.locationUrl('home', ''); } $scope.countdown = countdownArray; _self.loopTime(); }); }); }, 1000); } } return timeFunctiond; }; $scope.timeFunctiond().loopTime(); $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, getDealId: function(callback) { var _self = this; _self.getRouteParams(function(params) { var deal_id = params.deal_id.split("-", 1).join(""); callback(deal_id) }); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); _self.consoleLog("stateData : loadIn : ", loadIn); _self.consoleLog("stateData : doneIn : ", doneIn); _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); _self.consoleLog("dataSend : api : ", api); _self.consoleLog("dataSend : dataSend : ", dataSend); _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); callback(api, dataSend); }, getApiOk: function(output, callback) { var _self = this; var output_ok = []; if (output.ok == 1) { output_ok = output; } _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); _self.consoleLog("getApiOk : output_ok : ", output_ok); _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); callback(output_ok); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getApi : api : ", api); _self.consoleLog("getApi : dataSend : ", dataSend); _self.consoleLog("getApi : output : ", output); _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.getApiOk(output, function(output) { callback(output); }); }); }, dataCountdown: function(output, callback) { var _self = this; var countdownObject = { now: 0, state: output.deal_group_lifetime.lifetime_start_time, end: output.deal_group_lifetime.lifetime_end_time, day: 0, month: 0, year: 0, hours: 0, minutes: 0, seconds: 0, show: false }; $scope.countdown = countdownObject; callback(output); }, main: function() { var _self = this; _self.getDealId(function(deal_id) { $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(true, false); $scope.dataSet[0].dataSend = { 'txt_product_id': deal_id } _self.dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getRouteParams : dataSend : getApi : ", output); _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.dataCountdown(output.data, function(output) { setTimeout(function() { $scope.dataSet[0].dataArray = output; $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(false, true); }, 1000); }); }); }); }); } } return getFunction; }; $scope.getFunction().main(); }; return promise; });_ui_share_app.directive('componentFlashSaleIdProductTypeB', function($rootScope, $routeParams, $location) { var templateName = 'componentFlashSaleIdProductTypeB'; var componentMain = 'componentFlashSale'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', dealgroupid: '=dealgroupid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', 'topic_more': '?topicMore', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.component = "componentFlashSaleIdProductTypeB : "; /* api : 'deal_group/lists' txt_sortby : { 'product_lastest_create' , 'product_oldest_create' , 'product_title_a-z' , 'product_title_z-a' , 'root_category_index_asc' , 'root_category_index_desc' , } */ $scope.countdown = {}; $scope.dataSet = [{ api: "deal_group/id", dataSend: {}, dataArray: [], dataSendState: { load: false, done: false } }]; $scope.timeFunctiond = function() { var timeFunctiond = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { /* console.log(component, name, data); */ }); }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, momentUnix: function(callback) { var now = moment().unix(); callback(now); }, countdown: function(number, countdown, callback) { var _self = this; var timeCountdown = countdown.end - countdown.now; var duration = moment.duration(timeCountdown * 1000, "milliseconds"); if (timeCountdown > 0) { callback(number, duration, true); } else { callback(number, duration, false); } }, countdownArray: function(now, countdown, callback) { var _self = this; if (countdown.length != 0) { countdown.now = now; _self.countdown(0, countdown, function(number, duration, show) { countdown.day = (duration.days() <= 9) ? '0' + duration.days() : duration.days(); countdown.month = (duration.months() <= 9) ? '0' + duration.months() : duration.months(); countdown.year = (duration.years() <= 9) ? '0' + duration.years() : duration.years(); countdown.hours = (duration.hours() <= 9) ? '0' + duration.hours() : duration.hours(); countdown.minutes = (duration.minutes() <= 9) ? '0' + duration.minutes() : duration.minutes(); countdown.seconds = (duration.seconds() <= 9) ? '0' + duration.seconds() : duration.seconds(); countdown.show = show; }); callback(countdown); } else { callback(countdown); } }, loopTime: function() { var _self = this; var timeout_promise = $timeout(function() { _self.momentUnix(function(now) { _self.countdownArray(now, $scope.countdown, function(countdownArray) { if (!countdownArray.show) { _self.locationUrl('home', ''); } $scope.countdown = countdownArray; _self.loopTime(); }); }); }, 1000); } } return timeFunctiond; }; $scope.timeFunctiond().loopTime(); $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, getDealId: function(callback) { var _self = this; _self.getRouteParams(function(params) { var deal_id = params.deal_id.split("-", 1).join(""); callback(deal_id) }); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); _self.consoleLog("stateData : loadIn : ", loadIn); _self.consoleLog("stateData : doneIn : ", doneIn); _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); _self.consoleLog("dataSend : api : ", api); _self.consoleLog("dataSend : dataSend : ", dataSend); _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); callback(api, dataSend); }, getApiOk: function(output, callback) { var _self = this; var output_ok = []; if (output.ok == 1) { output_ok = output; } _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); _self.consoleLog("getApiOk : output_ok : ", output_ok); _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); callback(output_ok); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getApi : api : ", api); _self.consoleLog("getApi : dataSend : ", dataSend); _self.consoleLog("getApi : output : ", output); _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.getApiOk(output, function(output) { callback(output); }); }); }, dataCountdown: function(output, callback) { var _self = this; var countdownObject = { now: 0, state: output.deal_group_lifetime.lifetime_start_time, end: output.deal_group_lifetime.lifetime_end_time, day: 0, month: 0, year: 0, hours: 0, minutes: 0, seconds: 0, show: false }; $scope.countdown = countdownObject; callback(output); }, main: function() { var _self = this; _self.getDealId(function(deal_id) { $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(true, false); $scope.dataSet[0].dataSend = { 'txt_product_id': deal_id } _self.dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getRouteParams : dataSend : getApi : ", output); _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.dataCountdown(output.data, function(output) { setTimeout(function() { $scope.dataSet[0].dataArray = output; $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(false, true); }, 1000); }); }); }); }); } } return getFunction; }; $scope.getFunction().main(); }; return promise; });_ui_share_app.directive('componentFlashSaleIdTypeA', function($rootScope, $routeParams, $location) { var templateName = 'componentFlashSaleIdTypeA'; var componentMain = 'componentFlashSale'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', dealgroupid: '=dealgroupid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', 'topic_more': '?topicMore', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.component = "componentFlashSaleIdTypeA : "; /* api : 'deal_group/lists' txt_sortby : { 'product_lastest_create' , 'product_oldest_create' , 'product_title_a-z' , 'product_title_z-a' , 'root_category_index_asc' , 'root_category_index_desc' , } */ $scope.dataSet = [{ api: "deal_group/id", dataSend: {}, dataArray: [], dataSendState: { load: false, done: false } }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { /* console.log(component, name, data); */ }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); _self.consoleLog("stateData : loadIn : ", loadIn); _self.consoleLog("stateData : doneIn : ", doneIn); _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); _self.consoleLog("dataSend : api : ", api); _self.consoleLog("dataSend : dataSend : ", dataSend); _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); callback(api, dataSend); }, getApiOk: function(output, callback) { var _self = this; var output_ok = []; if (output.ok == 1) { output_ok = output; } _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); _self.consoleLog("getApiOk : output_ok : ", output_ok); _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); callback(output_ok); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getApi : api : ", api); _self.consoleLog("getApi : dataSend : ", dataSend); _self.consoleLog("getApi : output : ", output); _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.getApiOk(output, function(output) { callback(output); }); }); }, main: function() { var _self = this; $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(true, false); $scope.dataSet[0].dataSend = { 'txt_product_id': $scope.dealgroupid } _self.dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getRouteParams : dataSend : getApi : ", output); _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); $scope.dataSet[0].dataArray = output.data; setTimeout(function() { $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(false, true); }, 1000); }); }); } } return getFunction; }; $scope.getFunction().main(); }; return promise; });_ui_share_app.directive('componentFlashSaleIdTypeB', function($rootScope, $routeParams, $location) { var templateName = 'componentFlashSaleIdTypeB'; var componentMain = 'componentFlashSale'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', dealgroupid: '=dealgroupid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', 'topic_more': '?topicMore', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.component = "componentFlashSaleIdTypeB : "; /* api : 'deal_group/lists' txt_sortby : { 'product_lastest_create' , 'product_oldest_create' , 'product_title_a-z' , 'product_title_z-a' , 'root_category_index_asc' , 'root_category_index_desc' , } */ $scope.dataSet = [{ api: "deal_group/id", dataSend: {}, dataArray: [], dataSendState: { load: false, done: false } }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { /* console.log(component, name, data); */ }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); _self.consoleLog("stateData : loadIn : ", loadIn); _self.consoleLog("stateData : doneIn : ", doneIn); _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); _self.consoleLog("dataSend : api : ", api); _self.consoleLog("dataSend : dataSend : ", dataSend); _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); callback(api, dataSend); }, getApiOk: function(output, callback) { var _self = this; var output_ok = []; if (output.ok == 1) { output_ok = output; } _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); _self.consoleLog("getApiOk : output_ok : ", output_ok); _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); callback(output_ok); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getApi : api : ", api); _self.consoleLog("getApi : dataSend : ", dataSend); _self.consoleLog("getApi : output : ", output); _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.getApiOk(output, function(output) { callback(output); }); }); }, main: function() { var _self = this; $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(true, false); $scope.dataSet[0].dataSend = { 'txt_product_id': $scope.dealgroupid } _self.dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getRouteParams : dataSend : getApi : ", output); _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); $scope.dataSet[0].dataArray = output.data; setTimeout(function() { $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(false, true); }, 1000); }); }); } } return getFunction; }; $scope.getFunction().main(); }; return promise; });_ui_share_app.directive('componentFlashSaleListsTypeA', function($rootScope, $routeParams, $location) { var templateName = 'componentFlashSaleListsTypeA'; var componentMain = 'componentFlashSale'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.component = "componentFlashSaleListsTypeA : "; /* api : 'deal_group/lists' txt_sortby : { 'product_lastest_create' , 'product_oldest_create' , 'product_title_a-z' , 'product_title_z-a' , 'root_category_index_asc' , 'root_category_index_desc' , } */ $scope.countdown = []; $scope.dataSet = [{ api: "deal_group/lists", dataSend: {}, dataArray: [], dataSendState: { load: false, done: false } }]; $scope.timeFunctiond = function() { var timeFunctiond = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { /* console.log(component, name, data); */ }); }, momentUnix: function(callback) { var now = moment().unix(); callback(now); }, countdown: function(number, countdown, callback) { var _self = this; var timeCountdown = countdown.end - countdown.now; var duration = moment.duration(timeCountdown * 1000, "milliseconds"); if (timeCountdown > 0) { callback(number, duration, true); } else { callback(number, duration, false); } }, countdownArray: function(now, countdown, callback) { var _self = this; if (countdown.length != 0) { for (var i = 0; i < countdown.length; i++) { countdown[i].now = now; _self.countdown(i, countdown[i], function(number, duration, show) { countdown[number].day = (duration.days() <= 9) ? '0' + duration.days() : duration.days(); countdown[number].month = (duration.months() <= 9) ? '0' + duration.months() : duration.months(); countdown[number].year = (duration.years() <= 9) ? '0' + duration.years() : duration.years(); countdown[number].hours = (duration.hours() <= 9) ? '0' + duration.hours() : duration.hours(); countdown[number].minutes = (duration.minutes() <= 9) ? '0' + duration.minutes() : duration.minutes(); countdown[number].seconds = (duration.seconds() <= 9) ? '0' + duration.seconds() : duration.seconds(); countdown[number].show = show; if ((i + 1) == countdown.length) { callback(countdown); } }); } } else { callback(countdown); } }, loopTime: function() { var _self = this; var timeout_promise = $timeout(function() { _self.momentUnix(function(now) { _self.countdownArray(now, $scope.countdown, function(countdownArray) { $scope.countdown = countdownArray; _self.loopTime(); }); }); }, 1000); } } return timeFunctiond; }; $scope.timeFunctiond().loopTime(); $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, id, title) { var _self = this; title = _self.titleUrl(title); $location.url(template + '/' + id + '-' + title).replace(); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, momentUnix: function(callback) { var now = moment().unix(); callback(now); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); _self.consoleLog("stateData : loadIn : ", loadIn); _self.consoleLog("stateData : doneIn : ", doneIn); _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); _self.consoleLog("dataSend : api : ", api); _self.consoleLog("dataSend : dataSend : ", dataSend); _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); callback(api, dataSend); }, getApiOk: function(output, callback) { var _self = this; var output_ok = []; if (output.ok == 1) { output_ok = output; } _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); _self.consoleLog("getApiOk : output_ok : ", output_ok); _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); callback(output_ok); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getApi : api : ", api); _self.consoleLog("getApi : dataSend : ", dataSend); _self.consoleLog("getApi : output : ", output); _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.getApiOk(output, function(output) { callback(output); }); }); }, dataCountdown: function(output, callback) { var _self = this; if (output.data.dataList.length != 0) { for (i = 0; i < output.data.dataList.length; i++) { var countdownObject = { now: 0, state: output.data.dataList[i].deal_group_lifetime.lifetime_start_time, end: output.data.dataList[i].deal_group_lifetime.lifetime_end_time, day: 0, month: 0, year: 0, hours: 0, minutes: 0, seconds: 0, show: false }; $scope.countdown.push(countdownObject); _self.consoleLog("getRouteParams : dataCountdown : i : ", i); if ((i + 1) == output.data.dataList.length) { callback(output); } } } else { callback(output); } }, main: function() { var _self = this; _self.momentUnix(function(now) { $scope.dataSet[0].dataSendState = _self.stateData(true, false); var filter_json = {} $scope.dataSet[0].dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_lifetime_from': now, 'txt_lifetime_to': 0, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) } _self.dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getRouteParams : dataSend : getApi : ", output); _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.dataCountdown(output, function(output) { $scope.dataSet[0].dataArray = output; $scope.dataSet[0].dataSendState = _self.stateData(false, true); }); }); }); }); } } return getFunction; }; $scope.getFunction().main(); }; return promise; });_ui_share_app.directive('componentFlashSaleListsTypeB', function($rootScope, $routeParams, $location) { var templateName = 'componentFlashSaleListsTypeB'; var componentMain = 'componentFlashSale'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.transclude = { 'topic_top_main': '?topicTopMain', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.component = "componentFlashSaleListsTypeB : "; /* api : 'deal_group/lists' txt_sortby : { 'product_lastest_create' , 'product_oldest_create' , 'product_title_a-z' , 'product_title_z-a' , 'root_category_index_asc' , 'root_category_index_desc' , } */ $scope.countdown = []; $scope.dataSet = [{ api: "deal_group/lists", dataSend: {}, dataArray: [], dataSendState: { load: false, done: false } }]; $scope.timeFunctiond = function() { var timeFunctiond = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { /* console.log(component, name, data); */ }); }, momentUnix: function(callback) { var now = moment().unix(); callback(now); }, countdown: function(number, countdown, callback) { var _self = this; var timeCountdown = countdown.end - countdown.now; var duration = moment.duration(timeCountdown * 1000, "milliseconds"); if (timeCountdown > 0) { callback(number, duration, true); } else { callback(number, duration, false); } }, countdownArray: function(now, countdown, callback) { var _self = this; if (countdown.length != 0) { for (var i = 0; i < countdown.length; i++) { countdown[i].now = now; _self.countdown(i, countdown[i], function(number, duration, show) { countdown[number].day = (duration.days() <= 9) ? '0' + duration.days() : duration.days(); countdown[number].month = (duration.months() <= 9) ? '0' + duration.months() : duration.months(); countdown[number].year = (duration.years() <= 9) ? '0' + duration.years() : duration.years(); countdown[number].hours = (duration.hours() <= 9) ? '0' + duration.hours() : duration.hours(); countdown[number].minutes = (duration.minutes() <= 9) ? '0' + duration.minutes() : duration.minutes(); countdown[number].seconds = (duration.seconds() <= 9) ? '0' + duration.seconds() : duration.seconds(); countdown[number].show = show; if ((i + 1) == countdown.length) { callback(countdown); } }); } } else { callback(countdown); } }, loopTime: function() { var _self = this; var timeout_promise = $timeout(function() { _self.momentUnix(function(now) { _self.countdownArray(now, $scope.countdown, function(countdownArray) { $scope.countdown = countdownArray; _self.loopTime(); }); }); }, 1000); } } return timeFunctiond; }; $scope.timeFunctiond().loopTime(); $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, id, title) { var _self = this; title = _self.titleUrl(title); $location.url(template + '/' + id + '-' + title).replace(); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, momentUnix: function(callback) { var now = moment().unix(); callback(now); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); _self.consoleLog("stateData : loadIn : ", loadIn); _self.consoleLog("stateData : doneIn : ", doneIn); _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); _self.consoleLog("dataSend : api : ", api); _self.consoleLog("dataSend : dataSend : ", dataSend); _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); callback(api, dataSend); }, getApiOk: function(output, callback) { var _self = this; var output_ok = []; if (output.ok == 1) { output_ok = output; } _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); _self.consoleLog("getApiOk : output_ok : ", output_ok); _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); callback(output_ok); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getApi : api : ", api); _self.consoleLog("getApi : dataSend : ", dataSend); _self.consoleLog("getApi : output : ", output); _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.getApiOk(output, function(output) { callback(output); }); }); }, dataCountdownUse: function(output, callback) { var use = (output.length > 0) ? true : false; callback(use); }, dataCountdown: function(output, callback) { var _self = this; if (output.data.dataList.length != 0) { for (i = 0; i < output.data.dataList.length; i++) { var countdownObject = { now: 0, state: output.data.dataList[i].deal_group_lifetime.lifetime_start_time, end: output.data.dataList[i].deal_group_lifetime.lifetime_end_time, day: 0, month: 0, year: 0, hours: 0, minutes: 0, seconds: 0, show: false }; $scope.countdown.push(countdownObject); _self.consoleLog("getRouteParams : dataCountdown : i : ", i); if ((i + 1) == output.data.dataList.length) { callback(output); } } } else { callback(output); } }, main: function() { var _self = this; _self.momentUnix(function(now) { $scope.dataSet[0].dataSendState = _self.stateData(true, false); var filter_json = {} $scope.dataSet[0].dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_lifetime_from': now, 'txt_lifetime_to': 0, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) } _self.dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getRouteParams : dataSend : getApi : ", output); _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.dataCountdownUse(output, function(res_use) { if (res_use) { _self.dataCountdown(output, function(output) { $scope.dataSet[0].dataArray = output; }); } $scope.dataSet[0].dataSendState = _self.stateData(false, true); }); }); }); }); } } return getFunction; }; $scope.getFunction().main(); }; return promise; });/*_ui_share_app.directive('componentFooter', function($rootScope, $routeParams) { var templateName = 'componentFooter'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id: '=', background: '@', primary: '@', secondary: '@', name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) {}; return promise; });*/ _ui_share_app.factory('$componentFooter', function componentFooter($routeParams, $timeout) { return });_ui_share_app.directive('componentFooterD', function($rootScope, $routeParams) { var templateName = 'componentFooterD'; var componentMain = 'componentFooter'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { background_: '@background', color_: '@color', color_hover: '@colorhover', size_social: '@sizesocial', icnt_icon: '@icnticon', icon_: '@icon', icon_hover: '@iconhover', icnt_icon_hover: '@icnticonhover', imgPath: '@imgPath', imglogo: '@imglogo', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_one': '?footerOne', 'footer_two': '?footerTwo', 'footer_three': '?footerThree', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { if ($scope.size_social == undefined || $scope.size_social == 'null') { $scope.size_social = '30px'; } if ($scope.icnt_icon == undefined || $scope.icnt_icon == 'null') { $scope.icnt_icon = 'icnt_outline_'; } if ($scope.icon_ == undefined || $scope.icon_ == 'null') { $scope.icon_ = '01_grey2@2x'; } if ($scope.icnt_icon_hover == undefined || $scope.icnt_icon_hover == 'null') { $scope.icnt_icon_hover = 'icnt_fill_'; } if ($scope.icon_hover == undefined || $scope.icon_hover == 'null') { $scope.icon_hover = '01_grey2@2x'; } /*alert("Foter" + " : " + $scope.size_social + " : " + $scope.icnt_icon + " : " + $scope.icon_ + " : " + $scope.icnt_icon_hover + " : " + $scope.icon_hover);*/ }; return promise; });_ui_share_app.directive('componentFooterE', function($rootScope, $routeParams) { var templateName = 'componentFooterE'; var componentMain = 'componentFooter'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { background_: '@background', color_: '@color', color_hover: '@colorhover', size_social: '@sizesocial', icnt_icon: '@icnticon', icon_: '@icon', icon_hover: '@iconhover', icnt_icon_hover: '@icnticonhover', imgPath: '@imgPath', imglogo: '@imglogo', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_one': '?footerOne', 'footer_two': '?footerTwo', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { if ($scope.size_social == undefined || $scope.size_social == 'null') { $scope.size_social = '40px'; } if ($scope.icnt_icon == undefined || $scope.icnt_icon == 'null') { $scope.icnt_icon = 'icnt_outline_'; } if ($scope.icon_ == undefined || $scope.icon_ == 'null') { $scope.icon_ = '01_grey2@2x'; } if ($scope.icnt_icon_hover == undefined || $scope.icnt_icon_hover == 'null') { $scope.icnt_icon_hover = 'icnt_fill_'; } if ($scope.icon_hover == undefined || $scope.icon_hover == 'null') { $scope.icon_hover = '01_grey2@2x'; } /*alert("Foter" + " : " + $scope.size_social + " : " + $scope.icnt_icon + " : " + $scope.icon_ + " : " + $scope.icnt_icon_hover + " : " + $scope.icon_hover);*/ }; return promise; });_ui_share_app.directive('componentFooterFourColumn', function($rootScope, $routeParams) { var templateName = 'componentFooterFourColumn'; var componentMain = 'componentFooter'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { backgroundclass_: '@backgroundclass', background_: '@background', headline_: '@headline', color_: '@color', color_hover: '@colorhover', size_social: '@sizesocial', icnt_icon: '@icnticon', icon_: '@icon', icon_hover: '@iconhover', icnt_icon_hover: '@icnticonhover', imgPath: '@imgPath', imglogo: '@imglogo', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_one': '?footerOne', 'footer_two': '?footerTwo', 'footer_three': '?footerThree', 'footer_four': '?footerFour', 'footer_bottom': '?footerBottom', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { if ($scope.size_social == undefined || $scope.size_social == 'null') { $scope.size_social = '40px'; } if ($scope.icnt_icon == undefined || $scope.icnt_icon == 'null') { $scope.icnt_icon = 'icnt_outline_'; } if ($scope.icon_ == undefined || $scope.icon_ == 'null') { $scope.icon_ = '01_grey2@2x'; } if ($scope.icnt_icon_hover == undefined || $scope.icnt_icon_hover == 'null') { $scope.icnt_icon_hover = 'icnt_fill_'; } if ($scope.icon_hover == undefined || $scope.icon_hover == 'null') { $scope.icon_hover = '01_grey2@2x'; } /*alert("Foter" + " : " + $scope.size_social + " : " + $scope.icnt_icon + " : " + $scope.icon_ + " : " + $scope.icnt_icon_hover + " : " + $scope.icon_hover);*/ }; return promise; });_ui_share_app.directive('componentFooterOneColumn', function($rootScope, $routeParams) { var templateName = 'componentFooterOneColumn'; var componentMain = 'componentFooter'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { background_: '@background', headline_: '@headline', color_: '@color', color_hover: '@colorhover', size_social: '@sizesocial', icnt_icon: '@icnticon', icon_: '@icon', icon_hover: '@iconhover', icnt_icon_hover: '@icnticonhover', imgPath: '@imgPath', imglogo: '@imglogo', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_one': '?footerOne', 'footer_two': '?footerTwo', 'footer_three': '?footerThree', 'footer_bottom': '?footerBottom', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { if ($scope.size_social == undefined || $scope.size_social == 'null') { $scope.size_social = '40px'; } if ($scope.icnt_icon == undefined || $scope.icnt_icon == 'null') { $scope.icnt_icon = 'icnt_outline_'; } if ($scope.icon_ == undefined || $scope.icon_ == 'null') { $scope.icon_ = '01_grey2@2x'; } if ($scope.icnt_icon_hover == undefined || $scope.icnt_icon_hover == 'null') { $scope.icnt_icon_hover = 'icnt_fill_'; } if ($scope.icon_hover == undefined || $scope.icon_hover == 'null') { $scope.icon_hover = '01_grey2@2x'; } /*alert("Foter" + " : " + $scope.size_social + " : " + $scope.icnt_icon + " : " + $scope.icon_ + " : " + $scope.icnt_icon_hover + " : " + $scope.icon_hover);*/ }; return promise; });_ui_share_app.directive('componentFooterSocialnetworkA', function($rootScope, $routeParams) { var templateName = 'componentFooterSocialnetworkA'; var componentMain = 'componentFooter'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_right': '?footerRight', 'footer_left': '?footerLeft', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data = []; $scope.dataArray = []; $scope.line_friends = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; angular.forEach(e.data.shop_extend_data, function(i, key) { var obJect = $scope.buildSocialItemObject(key, i); $scope.dataArray.push(obJect); }); } }); }; $scope.getShopCurrent(); $scope.buildSocialItemObject = function(socialName, socialValue) { var nameSplit = socialName.split("_"); var promiseObject = { 'txt_social_name': nameSplit[0], 'txt_social_full_name': socialName, 'txt_social_value_name': socialValue, 'txt_social_value': socialValue || '' }; if (socialName.indexOf('line_url') != -1) { if (promiseObject.txt_social_value != "") { if (promiseObject.txt_social_value.indexOf('@') !== -1 || promiseObject.txt_social_value.indexOf('%40')) { var n = promiseObject.txt_social_value.replace('@', '%40'); promiseObject.txt_social_value = 'http://line.me/ti/p/' + n; } else { promiseObject.txt_social_value = 'http://line.me/ti/p/~' + promiseObject.txt_social_value; } $scope.line_friends[0] = promiseObject; } else { promiseObject.txt_social_value = ''; } } return promiseObject; }; $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentFooterThreeColumn', function($rootScope, $routeParams) { var templateName = 'componentFooterThreeColumn'; var componentMain = 'componentFooter'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { background_: '@background', headline_: '@headline', color_: '@color', color_hover: '@colorhover', size_social: '@sizesocial', icnt_icon: '@icnticon', icon_: '@icon', icon_hover: '@iconhover', icnt_icon_hover: '@icnticonhover', imgPath: '@imgPath', imglogo: '@imglogo', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_one': '?footerOne', 'footer_two': '?footerTwo', 'footer_three': '?footerThree', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { if ($scope.size_social == undefined || $scope.size_social == 'null') { $scope.size_social = '40px'; } if ($scope.icnt_icon == undefined || $scope.icnt_icon == 'null') { $scope.icnt_icon = 'icnt_outline_'; } if ($scope.icon_ == undefined || $scope.icon_ == 'null') { $scope.icon_ = '01_grey2@2x'; } if ($scope.icnt_icon_hover == undefined || $scope.icnt_icon_hover == 'null') { $scope.icnt_icon_hover = 'icnt_fill_'; } if ($scope.icon_hover == undefined || $scope.icon_hover == 'null') { $scope.icon_hover = '01_grey2@2x'; } /*alert("Foter" + " : " + $scope.size_social + " : " + $scope.icnt_icon + " : " + $scope.icon_ + " : " + $scope.icnt_icon_hover + " : " + $scope.icon_hover);*/ }; return promise; });_ui_share_app.directive('componentFooterTwoColumn', function($rootScope, $routeParams) { var templateName = 'componentFooterTwoColumn'; var componentMain = 'componentFooter'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { background_: '@background', headline_: '@headline', color_: '@color', color_hover: '@colorhover', size_social: '@sizesocial', icnt_icon: '@icnticon', icon_: '@icon', icon_hover: '@iconhover', icnt_icon_hover: '@icnticonhover', imgPath: '@imgPath', imglogo: '@imglogo', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_one': '?footerOne', 'footer_two': '?footerTwo', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { if ($scope.size_social == undefined || $scope.size_social == 'null') { $scope.size_social = '40px'; } if ($scope.icnt_icon == undefined || $scope.icnt_icon == 'null') { $scope.icnt_icon = 'icnt_outline_'; } if ($scope.icon_ == undefined || $scope.icon_ == 'null') { $scope.icon_ = '01_grey2@2x'; } if ($scope.icnt_icon_hover == undefined || $scope.icnt_icon_hover == 'null') { $scope.icnt_icon_hover = 'icnt_fill_'; } if ($scope.icon_hover == undefined || $scope.icon_hover == 'null') { $scope.icon_hover = '01_grey2@2x'; } /*alert("Foter" + " : " + $scope.size_social + " : " + $scope.icnt_icon + " : " + $scope.icon_ + " : " + $scope.icnt_icon_hover + " : " + $scope.icon_hover);*/ }; return promise; });_ui_share_app.directive('componentFooterShowblog', function($rootScope, $routeParams) { var componentMain = 'componentFooter'; var componentChild = 'showblog'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { color_: '@color', color_hover: '@colorhover', color_active: '@coloractive', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = false; $scope.getBloglists = function() { var dataSend = { 'cur_page': 1, 'per_page': 100 }; GAEAPI.get('blog/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data.dataList; } }); }; $scope.getBloglists(); }; return promise; });_ui_share_app.directive('componentFooterShowbrand', function($rootScope, $routeParams) { var componentMain = 'componentFooter'; var componentChild = 'showbrand'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { color_: '@color', color_hover: '@colorhover', color_active: '@coloractive', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.getBrandlists = function() { var dataSend = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 100, 'txt_sortby': 'referral_lastest_create', }; GAEAPI.get('referral/map', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; } }); }; $scope.getBrandlists(); }; return promise; });_ui_share_app.directive('componentFooterShowcontact', function($rootScope, $routeParams) { var componentMain = 'componentFooter'; var componentChild = 'showcontact'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { introtext: '@introtext', contactname: '@contactname', address: '@address', phone: '@phone', fax: '@fax', textfax: '@textfax', email: '@email', color_: '@color', color_hover: '@colorhover', color_active: '@coloractive', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._introtext = (typeof $scope.introtext !== 'undefined' && $scope.introtext !== '') ? $scope.introtext : 'show'; $scope._contactname = (typeof $scope.contactname !== 'undefined' && $scope.contactname !== '') ? $scope.contactname : 'show'; $scope._address = (typeof $scope.address !== 'undefined' && $scope.address !== '') ? $scope.address : 'show'; $scope._phone = (typeof $scope.phone !== 'undefined' && $scope.phone !== '') ? $scope.phone : 'show'; $scope._fax = (typeof $scope.fax !== 'undefined' && $scope.fax !== '') ? $scope.fax : 'show'; $scope._textfax = (typeof $scope.textfax !== 'undefined') ? $scope.textfax : 'Fax: '; $scope._email = (typeof $scope.email !== 'undefined' && $scope.email !== '') ? $scope.email : 'show'; $scope.data = false; $scope.copyRightTxt = ''; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; var datetime = new Date(); var year = datetime.getFullYear(); $scope.copyRightTxt = '© ' + year + ' ' + $scope.data.shop_name; console.log("FootershopCurrent", $scope.data); } }); }; $scope.getShopCurrent(); $scope.displayTelCode = function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.toTop = function() { $timeout(function() { $('html,body').animate({ scrollTop: 0 }, 'slow'); }, 100); }; }; return promise; });_ui_share_app.directive('componentFooterShowcopyright', function($rootScope, $routeParams) { var componentMain = 'componentFooter'; var componentChild = 'showcopyright'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { location_: '@location', color_: '@color', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = false; $scope.copyRightTxt = ''; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; var datetime = new Date(); var year = datetime.getFullYear(); $scope.copyRightTxt = '© ' + year + ' ' + $scope.data.shop_display_name; console.log("FootershopCurrent", $scope.copyRightTxt); } }); }; $scope.getShopCurrent(); }; return promise; });_ui_share_app.directive('componentFooterShowlogo', function($rootScope, $routeParams) { var componentMain = 'componentFooter'; var componentChild = 'showlogo'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imglogo_: '@imglogo' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = false; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; console.log("FootershopLogo", $scope.data); angular.forEach(e.data.shop_logo, function(i, key) { $scope.ItemObject(key, i); }); } }); }; $scope.getShopCurrent(); $scope.datalogo = false; $scope.ItemObject = function(iconName, iconValue) { var nameSplit = iconName.split("_"); if ($scope.imglogo_ == nameSplit[1]) { if (iconValue.length != 0) { console.log("FootershopLogo : $scope.imglogo_ : ", $scope.imglogo_); $scope.datalogo = iconValue[0].image_url; } else { $scope.datalogo = 'https://themedefault.getappeasy.com/extensions/themes/gae_default301/staticfiles/images/logo@2x.png'; } } } $scope.showDebug = function() { return (typeof $routeParams.debugfooter !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentFooterShowmaincategory', function($rootScope, $routeParams) { var componentMain = 'componentFooter'; var componentChild = 'showmaincategory'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { color_: '@color', color_hover: '@colorhover', color_active: '@coloractive', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.getCategorylists = function() { var option = {}; option.badge_id_array = [18]; var dataSend = { 'txt_referral_type_id': 11, 'txt_filter_json': JSON.stringify(option) }; GAEAPI.get('referral/map', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; } }); }; $scope.getCategorylists(); }; return promise; });_ui_share_app.directive('componentFooterShowmaincategoryfull', function($rootScope, $routeParams) { var componentMain = 'componentFooter'; var componentChild = 'showmaincategoryfull'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { color_: '@color', color_hover: '@colorhover', color_active: '@coloractive', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.getCategorylists = function() { var option = {}; var dataSend = { 'txt_referral_type_id': 11, 'txt_filter_json': JSON.stringify(option) }; GAEAPI.get('referral/map', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; } }); }; $scope.getCategorylists(); }; return promise; });_ui_share_app.directive('componentFooterShowpage', function($rootScope, $routeParams) { var componentMain = 'componentFooter'; var componentChild = 'showpage'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { color_: '@color', color_hover: '@colorhover', color_active: '@coloractive', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = false; $scope.getPagelists = function() { var dataSend = { 'cur_page': 1, 'per_page': 100 }; GAEAPI.get('page/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data.dataList; } }); }; $scope.getPagelists(); }; return promise; }); _ui_share_app.directive('componentFooterA', function ($rootScope, $routeParams) { var templateName = 'componentFooterA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', background: '@background', color: '@color' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_one':'?footerOne', 'footer_two':'?footerTwo', 'footer_three':'?footerThree', 'footer_four':'?footerFour' }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.directive('componentFooterB', function ($rootScope, $routeParams) { var templateName = 'componentFooterB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', background: '@background', color: '@color' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_one':'?footerOne', 'footer_two':'?footerTwo', 'footer_three':'?footerThree' }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.directive('componentFooterC', function ($rootScope, $routeParams) { var templateName = 'componentFooterC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { img: '@img', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.value('HTMLIZE_CONVERSIONS', [ { expr: /\n+?/g, value: '
' } ]); _ui_share_app.filter('htmlize', function(HTMLIZE_CONVERSIONS) { return function(string) { return HTMLIZE_CONVERSIONS.reduce(function(result, conversion) { return result.replace(conversion.expr, conversion.value); }, string || ''); }; }); _ui_share_app.directive('componentFooterCode', function($rootScope, $sce) { var templateName = 'componentFooterCode'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { code: '@code', backgroundcolor: '@backgroundcolor', headline: '@headline', textcolor: '@textcolor', textcolorhover: '@textcolorhover', col: '@col', footerthree: '@footerthree', imgPath: '@imgpath', imglogoleft: '@imglogoleft', imglogoright: '@imglogoright', imglogo: '@imglogo', name: '@name', callback: '@callback', sizelogosocial: '@sizelogosocial', typeSocialnetwork: '@typesocialnetwork', socialnetworkicon: '@socialnetworkicon', socialnetworkiconhover: '@socialnetworkiconhover', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'footer_one': '?footerOne', 'footer_one_top': '?footerOneTop', 'footer_one_bottom': '?footerOneBottom', 'footer_two': '?footerTwo', 'footer_two_top': '?footerTwoTop', 'footer_two_bottom': '?footerTwoBottom', 'footer_three': '?footerThree', 'footer_three_top': '?footerThreeTop', 'footer_three_bottom': '?footerThreeBottom', 'footer_four': '?footerFour', 'footer_four_top': '?footerFourTop', 'footer_four_bottom': '?footerFourBottom', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope.buildDummyData = function() { /* Address */ $scope.data.shop_extend_data.address = 'ส่วนการติดต่อ สามารถติดต่อบริษัทได้ที่
บริษัท ทดสอบ จำกัด เลขที่ 333/111 หมู่บ้านตัวอย่าง เขตเมืองเก่า แขวงพญาไทย กรุงเทพมหานคร 10100'; /* Phne*/ $scope.data.shop_extend_data.phone = '089-999-9999,089-747-7777,071-414-8888'; }; $scope.template = function(templateStringCode) { var str = _ui_share_host + templateName + '/template/' + templateStringCode + '.html'; return str.toString(); }; $scope.data = false; $scope.data_category = false; $scope.copyRightTxt = ''; if (!$scope.data) { GAEAPI.get('shop/current', {}, $scope).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.getsubAddress($scope.data.shop_extend_data.address); $scope.getsubPhone($scope.data.shop_extend_data.phone); $scope.getsubEmail($scope.data.shop_extend_data.mail); var d = new Date(); var n = d.getFullYear(); $scope.copyRightTxt = '© ' + n + ' ' + $scope.data.shop_name; /*console.log("phone123", $scope.data.shop_extend_data.phone); console.log('shop_display_name', $scope.data);*/ if (typeof $scope.data.shop_extend_data.contact_address === 'undefined' && typeof $scope.callback !== '' && $scope.callback !== '') { $scope.buildDummyData(); } } }); } $scope.getsubAddress = function(Address) { $scope.address_page = Address; /*console.log('address_page', $scope.address_page);*/ if ($scope.address_page !== '' && typeof $scope.address_page !== 'undefined') { $scope.address_page_split = $scope.address_page.split("_"); /* console.log('address_page_split', $scope.address_page_split);*/ $scope.address1_page = ''; $scope.address2_page = ''; if ($scope.address_page_split.length > 0) { $scope.address1_page = $scope.address_page_split[0]; } if ($scope.address_page_split.length > 1) { $scope.address2_page = $scope.address_page_split[1]; } } } $scope.getsubPhone = function(Phone) { $scope.phone_page = Phone; /*console.log('phone_page', $scope.phone_page);*/ if ($scope.phone_page !== '' && typeof $scope.phone_page !== 'undefined') { $scope.phone_page_split = $scope.phone_page.split(","); /*console.log('phone_page_split', $scope.phone_page_split);*/ $scope.phone1_page = ''; $scope.phone2_page = ''; if ($scope.phone_page_split.length > 0) { $scope.phone1_page_sub = $scope.phone_page_split[0].substring(1); $scope.phone1_page = $scope.phone_page_split[0]; } if ($scope.phone_page_split.length > 1) { $scope.phone2_page_sub = $scope.phone_page_split[1].substring(1); $scope.phone2_page = $scope.phone_page_split[1]; } } } $scope.getsubEmail = function(Email) { $scope.mail_page = Email; /*console.log('mail_page', $scope.mail_page);*/ if ($scope.mail_page !== '' && typeof $scope.mail_page !== 'undefined') { $scope.mail_page_split = $scope.mail_page.split(","); /*console.log('mail_page_split', $scope.mail_page_split);*/ $scope.mail1_page = ''; $scope.mail2_page = ''; if ($scope.mail_page_split.length > 0) { $scope.mail1_page_sub = $scope.mail_page_split[0].substring(1); $scope.mail1_page = $scope.mail_page_split[0]; } if ($scope.mail_page_split.length > 1) { $scope.mail2_page_sub = $scope.mail_page_split[1].substring(1); $scope.mail2_page = $scope.mail_page_split[1]; } } } if (!$scope.data_category) { GAEAPI.get('referral/map', { 'txt_referral_type_id': 11 }, $scope).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; console.log('data_category', $scope.data_category); } }); } $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.displayAddr = function(addStr){ var a = JSON.stringify(addStr); var b = a.replace('"','').replace('\n','
'); return b; } $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.toTop = function() { $timeout(function() { $('html,body').animate({ scrollTop: 0 }, 'slow'); }, 100); }; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopCurrent = e.data; } console.log("shopCurrent", $scope.shopCurrent); }); }; $scope.getShopCurrent(); /* Build title for Address link*/ $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* Get post list */ $scope.dataPost=[]; $scope.getPosts = function(){ var d = { 'cur_page':1, 'per_page':5, 'txt_sortby':'post_create_time_DESC', 'txt_filter_json':JSON.stringify({'badge_id_array':[18]}) }; GAEAPI.get('post/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataPost = e.data.dataList; } }); }; $scope.$watch('name',function(newValue,oldValue){ if(!newValue){ return; } switch(newValue){ case 'missmonribs': $scope.getPosts(); break; } }); }; return promise; });/* Cart displat at right side of page */ var $inforgotpasswordPopup = {}; /* params */ $inforgotpasswordPopup.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentForgotPassword/"; $inforgotpasswordPopup.templateRoot = 'root.php'; $inforgotpasswordPopup.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inforgotpasswordPopup.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inforgotpasswordPopup.install = function(shopId, customBuild) { /* dont install in (checkout, forgotpassword) */ /*if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/forgotpassword') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) {*/ this.templateRoot = 'root.php'; $.get($inforgotpasswordPopup.path + 'componentForgotPassword.css', function(response) { $('head').append(''); }); $.get($inforgotpasswordPopup.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inforgotpasswordPopup.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); /*}*/ }; $inforgotpasswordPopup.api = GURL.base_api_url(); /* Install */ /* forgotpassword model */ $inforgotpasswordPopup.forgotpassword = { email: '', }; $inforgotpasswordPopup.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', }; /* forgotpassword model */ /* validateForgotpassword */ $inforgotpasswordPopup.validateForgotpassword = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inforgotpasswordPopup.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inforgotpasswordPopup.error.email = false; $inforgotpasswordPopup.error.emailExist = false; $('#forgotpassword-email').css('border', ''); }, email: function() { var v = $('#forgotpassword-email-v1').val(); var t = this; if (v.length <= 0) { $inforgotpasswordPopup.shake(); $inforgotpasswordPopup.validateForgotpassword().emailInputNullError(); $inforgotpasswordPopup.error_email = false; $inforgotpasswordPopup.error_emailExist = false; return false; } else { var valid = $inforgotpasswordPopup.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inforgotpasswordPopup.shake(); $inforgotpasswordPopup.validateForgotpassword().emailInputError(); $inforgotpasswordPopup.error_email = true; return false; } else if (v.length > 0 && valid) { $inforgotpasswordPopup.validateForgotpassword().emailOk(); return true; } } }, emailOk: function() { $('#forgotpassword-email-v1').css('border', '2px solid green'); $inforgotpasswordPopup.validateForgotpassword().emailInputOk(); }, emailInputOk: function() { $("#forgotpassword-error-email").removeClass("error"); $("#forgotpassword-error-email").css('opacity', 0); }, emailError: function() { $("#forgotpassword-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inforgotpasswordPopup.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNullError: function() { $inforgotpasswordPopup.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); $("#forgotpassword-error-email").css('opacity', 1).html('กรุณากรอกอีเมล'); }, emailInputNotError: function() { $inforgotpasswordPopup.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); $("#forgotpassword-error-email").css('opacity', 1).html('ไม่พบอีเมลนี้ในระบบ'); }, resetEmail: function() { $("#forgotpassword-email-v1").css('border', ''); $("#forgotpassword-email-v1").val(''); $("#forgotpassword-error-email").css('opacity', 0); }, reset: function() { $inforgotpasswordPopup.validateForgotpassword().resetEmail(); }, }; return promise; }; /* validateForgotpassword */ /* load html */ $inforgotpasswordPopup.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inforgotpasswordPopup.whenOnLoad = function(shopId) {}; $inforgotpasswordPopup.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.forgotpassword_v1_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.forgotpassword_v1_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, forgotpasswordDone: function() { var load = $('.forgotpassword_v1_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").addClass("is_open"); }, 100); }, forgotpasswordUnDone: function() { var load = $('.forgotpassword_v1_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitForgotpassword */ $inforgotpasswordPopup.submitForgotpassword = function() { $inforgotpasswordPopup.forgotpassword.email = $('#forgotpassword-email-v1').val(); var userEmail = $inforgotpasswordPopup.forgotpassword.email; var userEmailValid = $inforgotpasswordPopup.validateForgotpassword().email(); console.log("Email State : userEmailValid : ", userEmailValid); if (userEmailValid) { $inforgotpasswordPopup.validateForgotpassword().checkEmail(userEmail, function(res_api_check_email) { console.log("inforgotpasswordPopup : ", "callback : res_api_check_email : ", res_api_check_email); if (res_api_check_email.ok == 0) { /* pass */ $inforgotpasswordPopup.sendSubmitForgotpassword(); } else { /* error not data email */ $inforgotpasswordPopup.validateForgotpassword().emailInputNotError(); } }); } else { $inforgotpasswordPopup.shake(); $inforgotpasswordPopup.validateForgotpassword().emailInputNullError(); } }; /* submitForgotpassword */ /* sendSubmitForgotpassword */ $inforgotpasswordPopup.sendSubmitForgotpassword = function() { $inforgotpasswordPopup.helper.pageLoad(); $inforgotpasswordPopup.forgotpassword.pressing = true; var userEmail = $inforgotpasswordPopup.forgotpassword.email; /* getapi */ var dataSend = { txt_email: userEmail }; GAEAPI.post('customer/forgot_password', dataSend).then(function(res_api) { console.log("customer/forgot_password callback : res_api : ", res_api); if (res_api.ok == 1) { $inforgotpasswordPopup.close(); $inforgotpasswordPopup.helper.pageUnLoad(); $inforgotpasswordPopup.helper.forgotpasswordDone(); } else { $inforgotpasswordPopup.helper.pageUnLoad(); alert("ผิดพลาด กรุณาลองใหม่อีกครั้ง"); } }); /* getapi */ }; /* sendSubmitForgotpassword */ $inforgotpasswordPopup.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inforgotpasswordPopup.isOpen = false; $inforgotpasswordPopup.open = function() { $inforgotpasswordPopup.validateForgotpassword().reset(); $(".forgotpassword_overlay").addClass("is_open"); $('body').css({ 'overflow': 'hidden', 'height': '100%' }); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inforgotpasswordPopup.submitForgotpassword(); } }); }; /* Open */ /* Close */ $inforgotpasswordPopup.close = function() { $(".forgotpassword_overlay").removeClass("is_open"); $(".forgotpassword.from_background").removeClass("is_open"); $('body').css({ 'overflow': 'auto' }); }; /* Close */ /* shake */ $inforgotpasswordPopup.shake = function() { $(".forgotpassword.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inforgotpasswordPopup.login = function() { $inforgotpasswordPopup.helper.forgotpasswordUnDone(); $inforgotpasswordPopup.close(); $inloginPopup.open(); } /* login */ /* toHome */ $inforgotpasswordPopup.toHome = function() { $inforgotpasswordPopup.helper.forgotpasswordUnDone(); window.location.href = 'home'; }; /* toHome */ /* Init */ /* Init */ /* Init */ /* $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { case 541: $inforgotpasswordPopup.install(currentShopId, false); break; case 635: $inforgotpasswordPopup.install(currentShopId, false); break; case 646: $inforgotpasswordPopup.install(currentShopId, false); break; case 647: $inforgotpasswordPopup.install(currentShopId, false); break; case 676: $inforgotpasswordPopup.install(currentShopId, false); break; case 717: $inforgotpasswordPopup.install(currentShopId, false); break; case 718: $inforgotpasswordPopup.install(currentShopId, false); break; case 723: $inforgotpasswordPopup.install(currentShopId, false); break; case 729: $inforgotpasswordPopup.install(currentShopId, false); break; case 732: $inforgotpasswordPopup.install(currentShopId, false); break; case 731: $inforgotpasswordPopup.install(currentShopId, false); break; default: break; } }); *//* Cart displat at right side of page */ var $inforgotpasswordPopupTypeCct = {}; /* params */ $inforgotpasswordPopupTypeCct.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentForgotPasswordTypeCct/"; $inforgotpasswordPopupTypeCct.templateRoot = 'root.php'; $inforgotpasswordPopupTypeCct.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inforgotpasswordPopupTypeCct.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inforgotpasswordPopupTypeCct.install = function(shopId, customBuild) { /* dont install in (checkout, forgotpassword) */ /*if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/forgotpassword') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) {*/ this.templateRoot = 'root.php'; $.get($inforgotpasswordPopupTypeCct.path + 'componentForgotPasswordTypeCct.css', function(response) { $('head').append(''); }); $.get($inforgotpasswordPopupTypeCct.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inforgotpasswordPopupTypeCct.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); /*}*/ }; $inforgotpasswordPopupTypeCct.api = GURL.base_api_url(); /* Install */ /* forgotpassword model */ $inforgotpasswordPopupTypeCct.forgotpassword = { email: '', }; $inforgotpasswordPopupTypeCct.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', }; /* forgotpassword model */ /* validateForgotpassword */ $inforgotpasswordPopupTypeCct.validateForgotpassword = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inforgotpasswordPopupTypeCct.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inforgotpasswordPopupTypeCct.error.email = false; $inforgotpasswordPopupTypeCct.error.emailExist = false; $('#forgotpassword-email').css('border', ''); }, email: function() { var v = $('#forgotpassword-email-v1').val(); var t = this; if (v.length <= 0) { $inforgotpasswordPopupTypeCct.shake(); $inforgotpasswordPopupTypeCct.validateForgotpassword().emailInputNullError(); $inforgotpasswordPopupTypeCct.error_email = false; $inforgotpasswordPopupTypeCct.error_emailExist = false; return false; } else { var valid = $inforgotpasswordPopupTypeCct.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inforgotpasswordPopupTypeCct.shake(); $inforgotpasswordPopupTypeCct.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeCct.error_email = true; return false; } else if (v.length > 0 && valid) { $inforgotpasswordPopupTypeCct.validateForgotpassword().emailOk(); return true; } } }, emailOk: function() { $('#forgotpassword-email-v1').css('border', '2px solid green'); $inforgotpasswordPopupTypeCct.validateForgotpassword().emailInputOk(); }, emailInputOk: function() { $("#forgotpassword-error-email").removeClass("error"); $("#forgotpassword-error-email").css('opacity', 0); }, emailError: function() { $("#forgotpassword-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inforgotpasswordPopupTypeCct.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNullError: function() { $inforgotpasswordPopupTypeCct.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); // $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, resetEmail: function() { $("#forgotpassword-email-v1").css('border', ''); $("#forgotpassword-email-v1").val(''); $("#forgotpassword-error-email").css('opacity', 0); }, reset: function() { $inforgotpasswordPopupTypeCct.validateForgotpassword().resetEmail(); }, }; return promise; }; /* validateForgotpassword */ /* load html */ $inforgotpasswordPopupTypeCct.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inforgotpasswordPopupTypeCct.whenOnLoad = function(shopId) {}; $inforgotpasswordPopupTypeCct.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.forgotpassword_vCct_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.forgotpassword_vCct_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, forgotpasswordDone: function() { var load = $('.forgotpassword_vCct_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").addClass("is_open"); }, 100); }, forgotpasswordUnDone: function() { var load = $('.forgotpassword_vCct_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitForgotpassword */ $inforgotpasswordPopupTypeCct.submitForgotpassword = function() { $inforgotpasswordPopupTypeCct.forgotpassword.email = $('#forgotpassword-email-v1').val(); var userEmail = $inforgotpasswordPopupTypeCct.forgotpassword.email; var userEmailValid = $inforgotpasswordPopupTypeCct.validateForgotpassword().email(); console.log("submitForgotpassword", "userEmailValid : ", userEmailValid); if (!userEmailValid) { console.log("submitForgotpassword", "return"); $inforgotpasswordPopupTypeCct.shake(); return; } $inforgotpasswordPopupTypeCct.validateForgotpassword().checkEmail(userEmail, function(resultCheck) { console.log("submitForgotpassword", resultCheck); if (resultCheck.ok == 1) { console.log('submitForgotpassword true'); $inforgotpasswordPopupTypeCct.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeCct.error.email = true; $inforgotpasswordPopupTypeCct.error.emailExist = true; } else { console.log('submitForgotpassword false'); return $inforgotpasswordPopupTypeCct.sendSubmitForgotpassword(false); } }); }; /* submitForgotpassword */ /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeCct.sendSubmitForgotpassword = function(reCheck) { $inforgotpasswordPopupTypeCct.forgotpassword.pressing = true; var userEmail = $inforgotpasswordPopupTypeCct.forgotpassword.email; console.log("sendSubmitForgotpassword userEmail : ", userEmail); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inforgotpasswordPopupTypeCct.validateForgotpassword().emailInputError(); } else { $inforgotpasswordPopupTypeCct.validateForgotpassword().emailOk(); } /* email */ if (userEmail.length > 0 && !$inforgotpasswordPopupTypeCct.helper.isEmail(userEmail)) { $inforgotpasswordPopupTypeCct.error_email = true; } else { $inforgotpasswordPopupTypeCct.error_email = false; } } /* loading */ $inforgotpasswordPopupTypeCct.helper.pageLoad(); var dataSend = { txt_email: userEmail }; GAEAPI.post('customer/forgot_password', dataSend).then(function(e) { console.log("sendSubmitForgotpassword : complete", e); if (e.ok == 1) { setTimeout(function() { $inforgotpasswordPopupTypeCct.close(); $inforgotpasswordPopupTypeCct.helper.pageUnLoad(); $inforgotpasswordPopupTypeCct.helper.forgotpasswordDone(); }, 100); } else { $inforgotpasswordPopupTypeCct.helper.pageUnLoad(); alert("ผิดพลาด กรุณาลองใหม่อีกครั้ง"); return; } }); /* loading */ }; /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeCct.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inforgotpasswordPopupTypeCct.isOpen = false; $inforgotpasswordPopupTypeCct.open = function() { $inforgotpasswordPopupTypeCct.validateForgotpassword().reset(); $(".forgotpassword_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'relative' }); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inforgotpasswordPopupTypeCct.submitForgotpassword(); } }); }; /* Open */ /* Close */ $inforgotpasswordPopupTypeCct.close = function() { $(".forgotpassword_overlay").removeClass("is_open"); $(".forgotpassword.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inforgotpasswordPopupTypeCct.shake = function() { $(".forgotpassword.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inforgotpasswordPopupTypeCct.login = function() { $inforgotpasswordPopupTypeCct.helper.forgotpasswordUnDone(); $inforgotpasswordPopupTypeCct.close(); $inloginPopupTypeCct.open(); } /* login */ /* toHome */ $inforgotpasswordPopupTypeCct.toHome = function() { $inforgotpasswordPopupTypeCct.helper.forgotpasswordUnDone(); window.location.href = 'home'; }; /* toHome */ /* Cart displat at right side of page */ var $inforgotpasswordPopupTypeElc = {}; /* params */ $inforgotpasswordPopupTypeElc.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentForgotPasswordTypeElc/"; $inforgotpasswordPopupTypeElc.templateRoot = 'root.php'; $inforgotpasswordPopupTypeElc.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inforgotpasswordPopupTypeElc.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inforgotpasswordPopupTypeElc.install = function(shopId, customBuild) { /* dont install in (checkout, forgotpassword) */ /*if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/forgotpassword') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) {*/ this.templateRoot = 'root.php'; $.get($inforgotpasswordPopupTypeElc.path + 'componentForgotPasswordTypeElc.css', function(response) { $('head').append(''); }); $.get($inforgotpasswordPopupTypeElc.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inforgotpasswordPopupTypeElc.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); /*}*/ }; $inforgotpasswordPopupTypeElc.api = GURL.base_api_url(); /* Install */ /* forgotpassword model */ $inforgotpasswordPopupTypeElc.forgotpassword = { email: '', }; $inforgotpasswordPopupTypeElc.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', }; /* forgotpassword model */ /* validateForgotpassword */ $inforgotpasswordPopupTypeElc.validateForgotpassword = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inforgotpasswordPopupTypeElc.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inforgotpasswordPopupTypeElc.error.email = false; $inforgotpasswordPopupTypeElc.error.emailExist = false; $('#forgotpassword-email').css('border', ''); }, email: function() { var v = $('#forgotpassword-email-v1').val(); var t = this; if (v.length <= 0) { $inforgotpasswordPopupTypeElc.shake(); $inforgotpasswordPopupTypeElc.validateForgotpassword().emailInputNullError(); $inforgotpasswordPopupTypeElc.error_email = false; $inforgotpasswordPopupTypeElc.error_emailExist = false; return false; } else { var valid = $inforgotpasswordPopupTypeElc.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inforgotpasswordPopupTypeElc.shake(); $inforgotpasswordPopupTypeElc.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeElc.error_email = true; return false; } else if (v.length > 0 && valid) { $inforgotpasswordPopupTypeElc.validateForgotpassword().emailOk(); return true; } } }, emailOk: function() { $('#forgotpassword-email-v1').css('border', '2px solid green'); $inforgotpasswordPopupTypeElc.validateForgotpassword().emailInputOk(); }, emailInputOk: function() { $("#forgotpassword-error-email").removeClass("error"); $("#forgotpassword-error-email").css('opacity', 0); }, emailError: function() { $("#forgotpassword-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inforgotpasswordPopupTypeElc.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNullError: function() { $inforgotpasswordPopupTypeElc.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); // $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, resetEmail: function() { $("#forgotpassword-email-v1").css('border', ''); $("#forgotpassword-email-v1").val(''); $("#forgotpassword-error-email").css('opacity', 0); }, reset: function() { $inforgotpasswordPopupTypeElc.validateForgotpassword().resetEmail(); }, }; return promise; }; /* validateForgotpassword */ /* load html */ $inforgotpasswordPopupTypeElc.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inforgotpasswordPopupTypeElc.whenOnLoad = function(shopId) {}; $inforgotpasswordPopupTypeElc.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.forgotpassword_vElc_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.forgotpassword_vElc_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, forgotpasswordDone: function() { var load = $('.forgotpassword_vElc_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").addClass("is_open"); }, 100); }, forgotpasswordUnDone: function() { var load = $('.forgotpassword_vElc_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitForgotpassword */ $inforgotpasswordPopupTypeElc.submitForgotpassword = function() { $inforgotpasswordPopupTypeElc.forgotpassword.email = $('#forgotpassword-email-v1').val(); var userEmail = $inforgotpasswordPopupTypeElc.forgotpassword.email; var userEmailValid = $inforgotpasswordPopupTypeElc.validateForgotpassword().email(); console.log("submitForgotpassword", "userEmailValid : ", userEmailValid); if (!userEmailValid) { console.log("submitForgotpassword", "return"); $inforgotpasswordPopupTypeElc.shake(); return; } $inforgotpasswordPopupTypeElc.validateForgotpassword().checkEmail(userEmail, function(resultCheck) { console.log("submitForgotpassword", resultCheck); if (resultCheck.ok == 1) { console.log('submitForgotpassword true'); $inforgotpasswordPopupTypeElc.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeElc.error.email = true; $inforgotpasswordPopupTypeElc.error.emailExist = true; } else { console.log('submitForgotpassword false'); return $inforgotpasswordPopupTypeElc.sendSubmitForgotpassword(false); } }); }; /* submitForgotpassword */ /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeElc.sendSubmitForgotpassword = function(reCheck) { $inforgotpasswordPopupTypeElc.forgotpassword.pressing = true; var userEmail = $inforgotpasswordPopupTypeElc.forgotpassword.email; console.log("sendSubmitForgotpassword userEmail : ", userEmail); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inforgotpasswordPopupTypeElc.validateForgotpassword().emailInputError(); } else { $inforgotpasswordPopupTypeElc.validateForgotpassword().emailOk(); } /* email */ if (userEmail.length > 0 && !$inforgotpasswordPopupTypeElc.helper.isEmail(userEmail)) { $inforgotpasswordPopupTypeElc.error_email = true; } else { $inforgotpasswordPopupTypeElc.error_email = false; } } /* loading */ $inforgotpasswordPopupTypeElc.helper.pageLoad(); var dataSend = { txt_email: userEmail }; GAEAPI.post('customer/forgot_password', dataSend).then(function(e) { console.log("sendSubmitForgotpassword : complete", e); if (e.ok == 1) { setTimeout(function() { $inforgotpasswordPopupTypeElc.close(); $inforgotpasswordPopupTypeElc.helper.pageUnLoad(); $inforgotpasswordPopupTypeElc.helper.forgotpasswordDone(); }, 100); } else { $inforgotpasswordPopupTypeElc.helper.pageUnLoad(); alert("ผิดพลาด กรุณาลองใหม่อีกครั้ง"); return; } }); /* loading */ }; /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeElc.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inforgotpasswordPopupTypeElc.isOpen = false; $inforgotpasswordPopupTypeElc.open = function() { $inforgotpasswordPopupTypeElc.validateForgotpassword().reset(); $(".forgotpassword_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'relative' }); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inforgotpasswordPopupTypeElc.submitForgotpassword(); } }); }; /* Open */ /* Close */ $inforgotpasswordPopupTypeElc.close = function() { $(".forgotpassword_overlay").removeClass("is_open"); $(".forgotpassword.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inforgotpasswordPopupTypeElc.shake = function() { $(".forgotpassword.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inforgotpasswordPopupTypeElc.login = function() { $inforgotpasswordPopupTypeElc.helper.forgotpasswordUnDone(); $inforgotpasswordPopupTypeElc.close(); $inregisterPopupTypeElc.open(); } /* login */ /* toHome */ $inforgotpasswordPopupTypeElc.toHome = function() { $inforgotpasswordPopupTypeElc.helper.forgotpasswordUnDone(); window.location.href = 'home'; }; /* toHome */ /* Init */ /* Init */ /* Init */ /* $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { case 541: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 635: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 646: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 647: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 676: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 717: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 718: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 723: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 729: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 732: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; case 731: $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; default: break; } }); *//* Cart displat at right side of page */ var $inforgotpasswordPopupTypeGrip = {}; /* params */ $inforgotpasswordPopupTypeGrip.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentForgotPasswordTypeGrip/"; $inforgotpasswordPopupTypeGrip.templateRoot = 'root.php'; $inforgotpasswordPopupTypeGrip.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inforgotpasswordPopupTypeGrip.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inforgotpasswordPopupTypeGrip.install = function(shopId, customBuild) { /* dont install in (checkout, forgotpassword) */ /*if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/forgotpassword') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) {*/ this.templateRoot = 'root.php'; $.get($inforgotpasswordPopupTypeGrip.path + 'componentForgotPasswordTypeGrip.css', function(response) { $('head').append(''); }); $.get($inforgotpasswordPopupTypeGrip.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inforgotpasswordPopupTypeGrip.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); /*}*/ }; $inforgotpasswordPopupTypeGrip.api = GURL.base_api_url(); /* Install */ /* forgotpassword model */ $inforgotpasswordPopupTypeGrip.forgotpassword = { email: '', }; $inforgotpasswordPopupTypeGrip.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', }; /* forgotpassword model */ /* validateForgotpassword */ $inforgotpasswordPopupTypeGrip.validateForgotpassword = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inforgotpasswordPopupTypeGrip.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inforgotpasswordPopupTypeGrip.error.email = false; $inforgotpasswordPopupTypeGrip.error.emailExist = false; $('#forgotpassword-email').css('border', ''); }, email: function() { var v = $('#forgotpassword-email-v1').val(); var t = this; if (v.length <= 0) { $inforgotpasswordPopupTypeGrip.shake(); $inforgotpasswordPopupTypeGrip.validateForgotpassword().emailInputNullError(); $inforgotpasswordPopupTypeGrip.error_email = false; $inforgotpasswordPopupTypeGrip.error_emailExist = false; return false; } else { var valid = $inforgotpasswordPopupTypeGrip.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inforgotpasswordPopupTypeGrip.shake(); $inforgotpasswordPopupTypeGrip.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeGrip.error_email = true; return false; } else if (v.length > 0 && valid) { $inforgotpasswordPopupTypeGrip.validateForgotpassword().emailOk(); return true; } } }, emailOk: function() { $('#forgotpassword-email-v1').css('border', '2px solid green'); $inforgotpasswordPopupTypeGrip.validateForgotpassword().emailInputOk(); }, emailInputOk: function() { $("#forgotpassword-error-email").removeClass("error"); $("#forgotpassword-error-email").css('opacity', 0); }, emailError: function() { $("#forgotpassword-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inforgotpasswordPopupTypeGrip.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNullError: function() { $inforgotpasswordPopupTypeGrip.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); // $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, resetEmail: function() { $("#forgotpassword-email-v1").css('border', ''); $("#forgotpassword-email-v1").val(''); $("#forgotpassword-error-email").css('opacity', 0); }, reset: function() { $inforgotpasswordPopupTypeGrip.validateForgotpassword().resetEmail(); }, }; return promise; }; /* validateForgotpassword */ /* load html */ $inforgotpasswordPopupTypeGrip.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inforgotpasswordPopupTypeGrip.whenOnLoad = function(shopId) {}; $inforgotpasswordPopupTypeGrip.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.forgotpassword_vGrip_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.forgotpassword_vGrip_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, forgotpasswordDone: function() { var load = $('.forgotpassword_vGrip_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").addClass("is_open"); }, 100); }, forgotpasswordUnDone: function() { var load = $('.forgotpassword_vGrip_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitForgotpassword */ $inforgotpasswordPopupTypeGrip.submitForgotpassword = function() { $inforgotpasswordPopupTypeGrip.forgotpassword.email = $('#forgotpassword-email-v1').val(); var userEmail = $inforgotpasswordPopupTypeGrip.forgotpassword.email; var userEmailValid = $inforgotpasswordPopupTypeGrip.validateForgotpassword().email(); console.log("submitForgotpassword", "userEmailValid : ", userEmailValid); if (!userEmailValid) { console.log("submitForgotpassword", "return"); $inforgotpasswordPopupTypeGrip.shake();inforgotpasswordPopupTypeGrip return; } $inforgotpasswordPopupTypeGrip.validateForgotpassword().checkEmail(userEmail, function(resultCheck) { console.log("submitForgotpassword", resultCheck); if (resultCheck.ok == 1) { console.log('submitForgotpassword true'); $inforgotpasswordPopupTypeGrip.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeGrip.error.email = true; $inforgotpasswordPopupTypeGrip.error.emailExist = true; } else { console.log('submitForgotpassword false'); return $inforgotpasswordPopupTypeGrip.sendSubmitForgotpassword(false); } }); }; /* submitForgotpassword */ /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeGrip.sendSubmitForgotpassword = function(reCheck) { $inforgotpasswordPopupTypeGrip.forgotpassword.pressing = true; var userEmail = $inforgotpasswordPopupTypeGrip.forgotpassword.email; console.log("sendSubmitForgotpassword userEmail : ", userEmail); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inforgotpasswordPopupTypeGrip.validateForgotpassword().emailInputError(); } else { $inforgotpasswordPopupTypeGrip.validateForgotpassword().emailOk(); } /* email */ if (userEmail.length > 0 && !$inforgotpasswordPopupTypeGrip.helper.isEmail(userEmail)) { $inforgotpasswordPopupTypeGrip.error_email = true; } else { $inforgotpasswordPopupTypeGrip.error_email = false; } } /* loading */ $inforgotpasswordPopupTypeGrip.helper.pageLoad(); var dataSend = { txt_email: userEmail }; GAEAPI.post('customer/forgot_password', dataSend).then(function(e) { console.log("sendSubmitForgotpassword : complete", e); if (e.ok == 1) { setTimeout(function() { $inforgotpasswordPopupTypeGrip.close(); $inforgotpasswordPopupTypeGrip.helper.pageUnLoad(); $inforgotpasswordPopupTypeGrip.helper.forgotpasswordDone(); }, 100); } else { $inforgotpasswordPopupTypeGrip.helper.pageUnLoad(); alert("ผิดพลาด กรุณาลองใหม่อีกครั้ง"); return; } }); /* loading */ }; /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeGrip.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inforgotpasswordPopupTypeGrip.isOpen = false; $inforgotpasswordPopupTypeGrip.open = function() { $inforgotpasswordPopupTypeGrip.validateForgotpassword().reset(); $(".forgotpassword_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'relative' }); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inforgotpasswordPopupTypeGrip.submitForgotpassword(); } }); }; /* Open */ /* Close */ $inforgotpasswordPopupTypeGrip.close = function() { $(".forgotpassword_overlay").removeClass("is_open"); $(".forgotpassword.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inforgotpasswordPopupTypeGrip.shake = function() { $(".forgotpassword.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inforgotpasswordPopupTypeGrip.login = function() { $inforgotpasswordPopupTypeGrip.helper.forgotpasswordUnDone(); $inforgotpasswordPopupTypeGrip.close(); $inloginPopupTypeGrip.open(); } /* login */ /* toHome */ $inforgotpasswordPopupTypeGrip.toHome = function() { $inforgotpasswordPopupTypeGrip.helper.forgotpasswordUnDone(); window.location.href = 'home'; }; /* toHome */ /* Init */ /* Init */ /* Init */ /* $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { case 541: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 635: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 646: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 647: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 676: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 717: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 718: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 723: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 729: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 732: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 731: $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; default: break; } }); *//* Cart displat at right side of page */ var $inforgotpasswordPopupTypeInfosat = {}; /* params */ $inforgotpasswordPopupTypeInfosat.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentForgotPasswordTypeInfosat/"; $inforgotpasswordPopupTypeInfosat.templateRoot = 'root.php'; $inforgotpasswordPopupTypeInfosat.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inforgotpasswordPopupTypeInfosat.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inforgotpasswordPopupTypeInfosat.install = function(shopId, customBuild) { /* dont install in (checkout, forgotpassword) */ /*if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/forgotpassword') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) {*/ this.templateRoot = 'root.php'; $.get($inforgotpasswordPopupTypeInfosat.path + 'componentForgotPasswordTypeInfosat.css', function(response) { $('head').append(''); }); $.get($inforgotpasswordPopupTypeInfosat.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inforgotpasswordPopupTypeInfosat.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); /*}*/ }; $inforgotpasswordPopupTypeInfosat.api = GURL.base_api_url(); /* Install */ /* forgotpassword model */ $inforgotpasswordPopupTypeInfosat.forgotpassword = { email: '', }; $inforgotpasswordPopupTypeInfosat.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', }; /* forgotpassword model */ /* validateForgotpassword */ $inforgotpasswordPopupTypeInfosat.validateForgotpassword = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inforgotpasswordPopupTypeInfosat.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inforgotpasswordPopupTypeInfosat.error.email = false; $inforgotpasswordPopupTypeInfosat.error.emailExist = false; $('#forgotpassword-email').css('border', ''); }, email: function() { var v = $('#forgotpassword-email-v1').val(); var t = this; if (v.length <= 0) { $inforgotpasswordPopupTypeInfosat.shake(); $inforgotpasswordPopupTypeInfosat.validateForgotpassword().emailInputNullError(); $inforgotpasswordPopupTypeInfosat.error_email = false; $inforgotpasswordPopupTypeInfosat.error_emailExist = false; return false; } else { var valid = $inforgotpasswordPopupTypeInfosat.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inforgotpasswordPopupTypeInfosat.shake(); $inforgotpasswordPopupTypeInfosat.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeInfosat.error_email = true; return false; } else if (v.length > 0 && valid) { $inforgotpasswordPopupTypeInfosat.validateForgotpassword().emailOk(); return true; } } }, emailOk: function() { $('#forgotpassword-email-v1').css('border', '2px solid green'); $inforgotpasswordPopupTypeInfosat.validateForgotpassword().emailInputOk(); }, emailInputOk: function() { $("#forgotpassword-error-email").removeClass("error"); $("#forgotpassword-error-email").css('opacity', 0); }, emailError: function() { $("#forgotpassword-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inforgotpasswordPopupTypeInfosat.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNullError: function() { $inforgotpasswordPopupTypeInfosat.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); // $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, resetEmail: function() { $("#forgotpassword-email-v1").css('border', ''); $("#forgotpassword-email-v1").val(''); $("#forgotpassword-error-email").css('opacity', 0); }, reset: function() { $inforgotpasswordPopupTypeInfosat.validateForgotpassword().resetEmail(); }, }; return promise; }; /* validateForgotpassword */ /* load html */ $inforgotpasswordPopupTypeInfosat.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inforgotpasswordPopupTypeInfosat.whenOnLoad = function(shopId) {}; $inforgotpasswordPopupTypeInfosat.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.forgotpassword_vInfosat_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.forgotpassword_vInfosat_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, forgotpasswordDone: function() { var load = $('.forgotpassword_vInfosat_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").addClass("is_open"); }, 100); }, forgotpasswordUnDone: function() { var load = $('.forgotpassword_vInfosat_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitForgotpassword */ $inforgotpasswordPopupTypeInfosat.submitForgotpassword = function() { $inforgotpasswordPopupTypeInfosat.forgotpassword.email = $('#forgotpassword-email-v1').val(); var userEmail = $inforgotpasswordPopupTypeInfosat.forgotpassword.email; var userEmailValid = $inforgotpasswordPopupTypeInfosat.validateForgotpassword().email(); console.log("submitForgotpassword", "userEmailValid : ", userEmailValid); if (!userEmailValid) { console.log("submitForgotpassword", "return"); $inforgotpasswordPopupTypeInfosat.shake(); return; } $inforgotpasswordPopupTypeInfosat.validateForgotpassword().checkEmail(userEmail, function(resultCheck) { console.log("submitForgotpassword", resultCheck); if (resultCheck.ok == 1) { console.log('submitForgotpassword true'); $inforgotpasswordPopupTypeInfosat.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeInfosat.error.email = true; $inforgotpasswordPopupTypeInfosat.error.emailExist = true; } else { console.log('submitForgotpassword false'); return $inforgotpasswordPopupTypeInfosat.sendSubmitForgotpassword(false); } }); }; /* submitForgotpassword */ /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeInfosat.sendSubmitForgotpassword = function(reCheck) { $inforgotpasswordPopupTypeInfosat.forgotpassword.pressing = true; var userEmail = $inforgotpasswordPopupTypeInfosat.forgotpassword.email; console.log("sendSubmitForgotpassword userEmail : ", userEmail); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inforgotpasswordPopupTypeInfosat.validateForgotpassword().emailInputError(); } else { $inforgotpasswordPopupTypeInfosat.validateForgotpassword().emailOk(); } /* email */ if (userEmail.length > 0 && !$inforgotpasswordPopupTypeInfosat.helper.isEmail(userEmail)) { $inforgotpasswordPopupTypeInfosat.error_email = true; } else { $inforgotpasswordPopupTypeInfosat.error_email = false; } } /* loading */ $inforgotpasswordPopupTypeInfosat.helper.pageLoad(); var dataSend = { txt_email: userEmail }; GAEAPI.post('customer/forgot_password', dataSend).then(function(e) { console.log("sendSubmitForgotpassword : complete", e); if (e.ok == 1) { setTimeout(function() { $inforgotpasswordPopupTypeInfosat.close(); $inforgotpasswordPopupTypeInfosat.helper.pageUnLoad(); $inforgotpasswordPopupTypeInfosat.helper.forgotpasswordDone(); }, 100); } else { $inforgotpasswordPopupTypeInfosat.helper.pageUnLoad(); alert("ผิดพลาด กรุณาลองใหม่อีกครั้ง"); return; } }); /* loading */ }; /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeInfosat.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inforgotpasswordPopupTypeInfosat.isOpen = false; $inforgotpasswordPopupTypeInfosat.open = function() { $inforgotpasswordPopupTypeInfosat.validateForgotpassword().reset(); $(".forgotpassword_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'fixed' }); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inforgotpasswordPopupTypeInfosat.submitForgotpassword(); } }); }; /* Open */ /* Close */ $inforgotpasswordPopupTypeInfosat.close = function() { $(".forgotpassword_overlay").removeClass("is_open"); $(".forgotpassword.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inforgotpasswordPopupTypeInfosat.shake = function() { $(".forgotpassword.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inforgotpasswordPopupTypeInfosat.login = function() { $inforgotpasswordPopupTypeInfosat.helper.forgotpasswordUnDone(); $inforgotpasswordPopupTypeInfosat.close(); $inregisterPopupTypeInfosat.open(); } /* login */ /* toHome */ $inforgotpasswordPopupTypeInfosat.toHome = function() { $inforgotpasswordPopupTypeInfosat.helper.forgotpasswordUnDone(); window.location.href = 'home'; }; /* toHome */ /* Init */ /* Init */ /* Init */ /* $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { case 541: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 635: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 646: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 647: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 676: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 717: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 718: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 723: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 729: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 732: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; case 731: $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; default: break; } }); *//* Cart displat at right side of page */ var $inforgotpasswordPopupTypeProin = {}; /* params */ $inforgotpasswordPopupTypeProin.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentForgotPasswordTypeProin/"; $inforgotpasswordPopupTypeProin.templateRoot = 'root.php'; $inforgotpasswordPopupTypeProin.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inforgotpasswordPopupTypeProin.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inforgotpasswordPopupTypeProin.install = function(shopId, logo, customBuild) { /* dont install in (checkout, forgotpassword) */ /*if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/forgotpassword') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) {*/ this.templateRoot = 'root.php'; var logoin = logo; $.get($inforgotpasswordPopupTypeProin.path + 'componentForgotPasswordTypeProin.css', function(response) { $('head').append(''); }); $.get($inforgotpasswordPopupTypeProin.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, logo: logoin, custom: customBuild, path: $inforgotpasswordPopupTypeProin.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); /*}*/ }; $inforgotpasswordPopupTypeProin.api = GURL.base_api_url(); /* Install */ /* forgotpassword model */ $inforgotpasswordPopupTypeProin.forgotpassword = { email: '', }; $inforgotpasswordPopupTypeProin.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', }; /* forgotpassword model */ /* validateForgotpassword */ $inforgotpasswordPopupTypeProin.validateForgotpassword = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inforgotpasswordPopupTypeProin.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inforgotpasswordPopupTypeProin.error.email = false; $inforgotpasswordPopupTypeProin.error.emailExist = false; $('#forgotpassword-email').css('border', ''); }, email: function() { var v = $('#forgotpassword-email-v1').val(); var t = this; if (v.length <= 0) { $inforgotpasswordPopupTypeProin.shake(); $inforgotpasswordPopupTypeProin.validateForgotpassword().emailInputNullError(); $inforgotpasswordPopupTypeProin.error_email = false; $inforgotpasswordPopupTypeProin.error_emailExist = false; return false; } else { var valid = $inforgotpasswordPopupTypeProin.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inforgotpasswordPopupTypeProin.shake(); $inforgotpasswordPopupTypeProin.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeProin.error_email = true; return false; } else if (v.length > 0 && valid) { $inforgotpasswordPopupTypeProin.validateForgotpassword().emailOk(); return true; } } }, emailOk: function() { $('#forgotpassword-email-v1').css('border', '2px solid green'); $inforgotpasswordPopupTypeProin.validateForgotpassword().emailInputOk(); }, emailInputOk: function() { $("#forgotpassword-error-email").removeClass("error"); $("#forgotpassword-error-email").css('opacity', 0); }, emailError: function() { $("#forgotpassword-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inforgotpasswordPopupTypeProin.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNullError: function() { $inforgotpasswordPopupTypeProin.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); // $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, resetEmail: function() { $("#forgotpassword-email-v1").css('border', ''); $("#forgotpassword-email-v1").val(''); $("#forgotpassword-error-email").css('opacity', 0); }, reset: function() { $inforgotpasswordPopupTypeProin.validateForgotpassword().resetEmail(); }, }; return promise; }; /* validateForgotpassword */ /* load html */ $inforgotpasswordPopupTypeProin.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inforgotpasswordPopupTypeProin.whenOnLoad = function(shopId) {}; $inforgotpasswordPopupTypeProin.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.forgotpassword_vProin_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.forgotpassword_vProin_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, forgotpasswordDone: function() { var load = $('.forgotpassword_vProin_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").addClass("is_open"); }, 100); }, forgotpasswordUnDone: function() { var load = $('.forgotpassword_vProin_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitForgotpassword */ $inforgotpasswordPopupTypeProin.submitForgotpassword = function() { $inforgotpasswordPopupTypeProin.forgotpassword.email = $('#forgotpassword-email-v1').val(); var userEmail = $inforgotpasswordPopupTypeProin.forgotpassword.email; var userEmailValid = $inforgotpasswordPopupTypeProin.validateForgotpassword().email(); console.log("submitForgotpassword", "userEmailValid : ", userEmailValid); if (!userEmailValid) { console.log("submitForgotpassword", "return"); $inforgotpasswordPopupTypeProin.shake(); return; } $inforgotpasswordPopupTypeProin.validateForgotpassword().checkEmail(userEmail, function(resultCheck) { console.log("submitForgotpassword", resultCheck); if (resultCheck.ok == 1) { console.log('submitForgotpassword true'); $inforgotpasswordPopupTypeProin.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeProin.error.email = true; $inforgotpasswordPopupTypeProin.error.emailExist = true; } else { console.log('submitForgotpassword false'); return $inforgotpasswordPopupTypeProin.sendSubmitForgotpassword(false); } }); }; /* submitForgotpassword */ /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeProin.sendSubmitForgotpassword = function(reCheck) { $inforgotpasswordPopupTypeProin.forgotpassword.pressing = true; var userEmail = $inforgotpasswordPopupTypeProin.forgotpassword.email; console.log("sendSubmitForgotpassword userEmail : ", userEmail); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inforgotpasswordPopupTypeProin.validateForgotpassword().emailInputError(); } else { $inforgotpasswordPopupTypeProin.validateForgotpassword().emailOk(); } /* email */ if (userEmail.length > 0 && !$inforgotpasswordPopupTypeProin.helper.isEmail(userEmail)) { $inforgotpasswordPopupTypeProin.error_email = true; } else { $inforgotpasswordPopupTypeProin.error_email = false; } } /* loading */ $inforgotpasswordPopupTypeProin.helper.pageLoad(); var dataSend = { txt_email: userEmail }; GAEAPI.post('customer/forgot_password', dataSend).then(function(e) { console.log("sendSubmitForgotpassword : complete", e); if (e.ok == 1) { setTimeout(function() { $inforgotpasswordPopupTypeProin.close(); $inforgotpasswordPopupTypeProin.helper.pageUnLoad(); $inforgotpasswordPopupTypeProin.helper.forgotpasswordDone(); }, 100); } else { $inforgotpasswordPopupTypeProin.helper.pageUnLoad(); alert("ผิดพลาด กรุณาลองใหม่อีกครั้ง"); return; } }); /* loading */ }; /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeProin.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inforgotpasswordPopupTypeProin.isOpen = false; $inforgotpasswordPopupTypeProin.open = function() { $inforgotpasswordPopupTypeProin.validateForgotpassword().reset(); $(".forgotpassword_overlay").addClass("is_open"); $('body').css({ 'overflow': 'hidden', 'height': '100%' }); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inforgotpasswordPopupTypeProin.submitForgotpassword(); } }); }; /* Open */ /* Close */ $inforgotpasswordPopupTypeProin.close = function() { $(".forgotpassword_overlay").removeClass("is_open"); $(".forgotpassword.from_background").removeClass("is_open"); $('body').css({ 'overflow': 'auto' }); }; /* Close */ /* shake */ $inforgotpasswordPopupTypeProin.shake = function() { $(".forgotpassword.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inforgotpasswordPopupTypeProin.login = function() { $inforgotpasswordPopupTypeProin.helper.forgotpasswordUnDone(); $inforgotpasswordPopupTypeProin.close(); $inloginPopup.open(); } /* login */ /* toHome */ $inforgotpasswordPopupTypeProin.toHome = function() { $inforgotpasswordPopupTypeProin.helper.forgotpasswordUnDone(); window.location.href = 'home'; }; /* toHome */ /* Init */ /* Init */ /* Init */ /* $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { case 541: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 635: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 646: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 647: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 676: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 717: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 718: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 723: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 729: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 732: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; case 731: $inforgotpasswordPopupTypeProin.install(currentShopId, false); break; default: break; } }); *//* Cart displat at right side of page */ var $inforgotpasswordPopupTypeSirikhu = {}; /* params */ $inforgotpasswordPopupTypeSirikhu.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentForgotPasswordTypeSirikhu/"; $inforgotpasswordPopupTypeSirikhu.templateRoot = 'root.php'; $inforgotpasswordPopupTypeSirikhu.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inforgotpasswordPopupTypeSirikhu.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inforgotpasswordPopupTypeSirikhu.install = function(shopId, customBuild) { /* dont install in (checkout, forgotpassword) */ /*if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/forgotpassword') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) {*/ this.templateRoot = 'root.php'; $.get($inforgotpasswordPopupTypeSirikhu.path + 'componentForgotPasswordTypeSirikhu.css', function(response) { $('head').append(''); }); $.get($inforgotpasswordPopupTypeSirikhu.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inforgotpasswordPopupTypeSirikhu.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); /*}*/ }; $inforgotpasswordPopupTypeSirikhu.api = GURL.base_api_url(); /* Install */ /* forgotpassword model */ $inforgotpasswordPopupTypeSirikhu.forgotpassword = { email: '', }; $inforgotpasswordPopupTypeSirikhu.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', }; /* forgotpassword model */ /* validateForgotpassword */ $inforgotpasswordPopupTypeSirikhu.validateForgotpassword = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inforgotpasswordPopupTypeSirikhu.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inforgotpasswordPopupTypeSirikhu.error.email = false; $inforgotpasswordPopupTypeSirikhu.error.emailExist = false; $('#forgotpassword-email').css('border', ''); }, email: function() { var v = $('#forgotpassword-email-v1').val(); var t = this; if (v.length <= 0) { $inforgotpasswordPopupTypeSirikhu.shake(); $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().emailInputNullError(); $inforgotpasswordPopupTypeSirikhu.error_email = false; $inforgotpasswordPopupTypeSirikhu.error_emailExist = false; return false; } else { var valid = $inforgotpasswordPopupTypeSirikhu.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inforgotpasswordPopupTypeSirikhu.shake(); $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeSirikhu.error_email = true; return false; } else if (v.length > 0 && valid) { $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().emailOk(); return true; } } }, emailOk: function() { $('#forgotpassword-email-v1').css('border', '2px solid green'); $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().emailInputOk(); }, emailInputOk: function() { $("#forgotpassword-error-email").removeClass("error"); $("#forgotpassword-error-email").css('opacity', 0); }, emailError: function() { $("#forgotpassword-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNullError: function() { $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().emailError(); $("#forgotpassword-error-email").addClass("error"); // $("#forgotpassword-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, resetEmail: function() { $("#forgotpassword-email-v1").css('border', ''); $("#forgotpassword-email-v1").val(''); $("#forgotpassword-error-email").css('opacity', 0); }, reset: function() { $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().resetEmail(); }, }; return promise; }; /* validateForgotpassword */ /* load html */ $inforgotpasswordPopupTypeSirikhu.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inforgotpasswordPopupTypeSirikhu.whenOnLoad = function(shopId) {}; $inforgotpasswordPopupTypeSirikhu.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.forgotpassword_vSirikhu_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.forgotpassword_vSirikhu_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, forgotpasswordDone: function() { var load = $('.forgotpassword_vSirikhu_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").addClass("is_open"); }, 100); }, forgotpasswordUnDone: function() { var load = $('.forgotpassword_vSirikhu_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".forgotpassword_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitForgotpassword */ $inforgotpasswordPopupTypeSirikhu.submitForgotpassword = function() { $inforgotpasswordPopupTypeSirikhu.forgotpassword.email = $('#forgotpassword-email-v1').val(); var userEmail = $inforgotpasswordPopupTypeSirikhu.forgotpassword.email; var userEmailValid = $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().email(); console.log("submitForgotpassword", "userEmailValid : ", userEmailValid); if (!userEmailValid) { console.log("submitForgotpassword", "return"); $inforgotpasswordPopupTypeSirikhu.shake(); return; } $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().checkEmail(userEmail, function(resultCheck) { console.log("submitForgotpassword", resultCheck); if (resultCheck.ok == 1) { console.log('submitForgotpassword true'); $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().emailInputError(); $inforgotpasswordPopupTypeSirikhu.error.email = true; $inforgotpasswordPopupTypeSirikhu.error.emailExist = true; } else { console.log('submitForgotpassword false'); return $inforgotpasswordPopupTypeSirikhu.sendSubmitForgotpassword(false); } }); }; /* submitForgotpassword */ /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeSirikhu.sendSubmitForgotpassword = function(reCheck) { $inforgotpasswordPopupTypeSirikhu.forgotpassword.pressing = true; var userEmail = $inforgotpasswordPopupTypeSirikhu.forgotpassword.email; console.log("sendSubmitForgotpassword userEmail : ", userEmail); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().emailInputError(); } else { $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().emailOk(); } /* email */ if (userEmail.length > 0 && !$inforgotpasswordPopupTypeSirikhu.helper.isEmail(userEmail)) { $inforgotpasswordPopupTypeSirikhu.error_email = true; } else { $inforgotpasswordPopupTypeSirikhu.error_email = false; } } /* loading */ $inforgotpasswordPopupTypeSirikhu.helper.pageLoad(); var dataSend = { txt_email: userEmail }; GAEAPI.post('customer/forgot_password', dataSend).then(function(e) { console.log("sendSubmitForgotpassword : complete", e); if (e.ok == 1) { setTimeout(function() { $inforgotpasswordPopupTypeSirikhu.close(); $inforgotpasswordPopupTypeSirikhu.helper.pageUnLoad(); $inforgotpasswordPopupTypeSirikhu.helper.forgotpasswordDone(); }, 100); } else { $inforgotpasswordPopupTypeSirikhu.helper.pageUnLoad(); alert("ผิดพลาด กรุณาลองใหม่อีกครั้ง"); return; } }); /* loading */ }; /* sendSubmitForgotpassword */ $inforgotpasswordPopupTypeSirikhu.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inforgotpasswordPopupTypeSirikhu.isOpen = false; $inforgotpasswordPopupTypeSirikhu.open = function() { $inforgotpasswordPopupTypeSirikhu.validateForgotpassword().reset(); $(".forgotpassword_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'auto', 'position': 'unset' }); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inforgotpasswordPopupTypeSirikhu.submitForgotpassword(); } }); }; /* Open */ /* Close */ $inforgotpasswordPopupTypeSirikhu.close = function() { $(".forgotpassword_overlay").removeClass("is_open"); $(".forgotpassword.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inforgotpasswordPopupTypeSirikhu.shake = function() { $(".forgotpassword.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".forgotpassword.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inforgotpasswordPopupTypeSirikhu.login = function() { $inforgotpasswordPopupTypeSirikhu.helper.forgotpasswordUnDone(); $inforgotpasswordPopupTypeSirikhu.close(); $inregisterPopupTypeSirikhu.open(); } /* login */ /* toHome */ $inforgotpasswordPopupTypeSirikhu.toHome = function() { $inforgotpasswordPopupTypeSirikhu.helper.forgotpasswordUnDone(); window.location.href = 'home'; }; /* toHome */ /* Init */ /* Init */ /* Init */ /* $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { case 541: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 635: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 646: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 647: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 676: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 717: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 718: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 723: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 729: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 732: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; case 731: $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; default: break; } }); */_ui_share_app.factory('$componentGallery', function componentGallery($routeParams, $timeout) { return });_ui_share_app.directive('componentGalleryIdA', function($rootScope, $routeParams) { var templateName = 'componentGalleryIdA'; var componentMain = 'componentGallery'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { galleryid: '@galleryid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataGallerylists = []; $scope.dataGallerylistsState = { load: false, done: false }; $scope.getGallery = function() { $scope.dataGallerylistsState = { load: true, done: false }; var d = { 'cur_page': 1, 'per_page': 100, }; GAEAPI.get('gallery/lists', d, $scope).then(function(e) { if (e.ok === 1) { $scope.dataGallerylists = e.data.dataList; } $scope.dataGallerylistsState = { load: false, done: true }; }); }; $scope.getGallery(); $scope.dataImagegrouplists = []; $scope.dataImagegrouplistsState = { load: false, done: false }; $scope.getImagegroup = function() { $scope.dataImagegrouplistsState = { load: true, done: false }; var filter_json_d = { 'gallery_id_array': [$routeParams.galleryid], } var d = { 'cur_page': 1, 'per_page': 50, 'txt_filter_json': JSON.stringify(filter_json_d) }; GAEAPI.get('image_group/lists', d, $scope).then(function(e) { if (e.ok === 1) { $scope.dataImagegrouplists = e.data.dataList; } $scope.dataImagegrouplistsState = { load: false, done: true }; }); }; $scope.getImagegroup(); $scope.dataImagelists = []; $scope.dataImagelistsState = { load: false, done: false }; $scope.getImage = function() { $scope.dataImagelistsState = { load: true, done: false }; var filter_json_d = { 'image_group_id_array': [$routeParams.imagegroupid], } var d = { 'cur_page': 1, 'per_page': 50, 'txt_filter_json': JSON.stringify(filter_json_d) }; GAEAPI.get('image/lists', d, $scope).then(function(e) { if (e.ok === 1) { $scope.dataImagelists = e.data.dataList; } $scope.dataImagelistsState = { load: false, done: true }; }); }; $scope.getImage(); $scope._viewRouteParams = function() { return $routeParams; }; $scope._makeDate = function(dateStr) { return (dateStr != "") ? moment(parseInt(dateStr) * 1000).format('LL') : ""; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentGalleryAlbum', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentGalleryAlbum'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', type: '@type', databuttonmore: '@databuttonmore', databuttonmoreloading: '@databuttonmoreloading', databuttonmoremore: '@databuttonmoremore', imgpath: '@imgpath', uselightbox: '@uselightbox', callback: '@callback', menu: '@menu', setall: '@setall', linitPtoto: '@linitptoto', fontcolor: '@fontcolor', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.setall = (typeof $scope.setall !== 'undefined' && $scope.setall !== '') ? $scope.setall : 'All'; $scope._databuttonmore = (typeof $scope.databuttonmore !== 'undefined' && $scope.databuttonmore !== '') ? $scope.databuttonmore : 'filled_button_small_round'; $scope._databuttonmoreloading = (typeof $scope.databuttonmoreloading !== 'undefined' && $scope.databuttonmoreloading !== '') ? $scope.databuttonmoreloading : 'Loading...'; $scope._databuttonmoremore = (typeof $scope.databuttonmoremore !== 'undefined' && $scope.databuttonmoremore !== '') ? $scope.databuttonmoremore : 'Load More'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; $scope._use_callback = (typeof $scope.callback !== 'undefined' && $scope.callback !== '') ? true : false; $scope._no_menu = (typeof $scope.menu !== 'undefined' && $scope.menu !== '') ? false : true; $scope._linitPtoto = (typeof $scope.linitPtoto !== 'undefined' && $scope.linitPtoto !== '') ? $scope.linitPtoto : 9; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._getIdFromUrl = function(rawRouteParams) { if (rawRouteParams != undefined) { var a = rawRouteParams; var b = a.split("-"); if (b.length > 0 && a.indexOf("-") !== -1) { return b[0]; } else { return a; } } }; /* Build dummy data by gallery type * @params {typeName} type of page * @return array */ $scope.buildDummyByType = function(typeName) { switch (typeName) { case 'gallery': var d = []; for (var i = 0; i < 6; i++) { var item = { 'gallery_badge': [{ badge_id: 18 }], 'gallery_id': (i + 1), 'gallery_name': 'Gallery ' + (i + 1), 'gallery_image': [{ 'image_url': 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }] }; d.push(item); } $scope.data_gallery_list = d; $scope.data_gallery_list_done = true; break; case 'gallery_id': var d = []; for (var i = 0; i < 6; i++) { var item = { 'gallery_badge': [{ badge_id: 18 }], 'image_group_id': 10 + (i + 1), 'image_group_name': 'Album list number ' + (i + 1), 'image_group_image': [{ 'image_url': 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }] }; d.push(item); } $scope.data_album_list = d; break; case 'photo_list': var d = []; for (var i = 0; i < 6; i++) { var item = { 'image_url': 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif', }; d.push(item); } $scope.data_photo_list = d; break; } }; /* Get all gellery for first time*/ $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, imageUrl: function(size, image_url) { var url = image_url.split("/"), length_url = url[url.length - 1]; url[url.length - 1] = size + '_' + length_url; return url.join("/"); }, resizeImageUrl: function(output, callback) { var _self = this; for (var i = 0; i <= output.length; i++) { if (i < output.length) { if (output[i].gallery_image.length != 0) { output[i].gallery_image[0].image_url = _self.imageUrl('t400', output[i].gallery_image[0].image_url); } } else { callback(output); } } }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.data_gallery_State = { load: true, done: false }; $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; $scope.galleryInit = function() { $scope.data_gallery_list = []; $scope.data_gallery_State.load = true; $scope.data_gallery_State.done = false; $scope.data_gallery_list_done = false; var d = { 'cur_page': 1, 'per_page': 30, 'txt_filter_json': JSON.stringify({ "badge_id_array": [18] }) }; GAEAPI.get('gallery/lists', d, $scope).then(function(e) { $scope.getData().consoleLog('gallery/lists : ', e); if (e.ok == 1) { $scope.getData().resizeImageUrl(e.data.dataList, function(output) { $scope.data_gallery_list = output; $scope.data_gallery_list_done = true; if ($scope.data_gallery_list.length <= 0 && $scope._use_callback) { $scope.buildDummyByType('gallery'); } }); } $scope.data_gallery_State.load = false; $scope.data_gallery_State.done = true; }); }; $scope.galleryInit(); $scope.data_gallery_id = []; $scope.data_gallery_id_done = false; $scope.galleryInitid = function(id_g) { // alert(id_g); $scope.data_gallery_id = []; var d = { 'txt_gallery_id': parseInt(id_g), }; GAEAPI.get('gallery/id', d, $scope).then(function(e) { $scope.data_gallery_id = (e.ok == 1) ? e.data : []; $scope.data_gallery_id_done = true; }); }; $scope.galleryInitid($scope._getIdFromUrl($routeParams.album_id)); // $scope.galleryInitid(); /* Get album list inside gallery id */ $scope.data_album_State = { load: true, done: false }; $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(gallery_id) { $scope.data_album_list = []; $scope.data_album_State.load = true; $scope.data_album_State.done = false; var d = { 'cur_page': 1, 'per_page': 500, 'txt_sortby': 'image_group_sort_index_ASC', 'txt_filter_json': JSON.stringify({ "gallery_id_array": [gallery_id] }) }; GAEAPI.get('image_group/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_album_list = (res.ok == 1) ? res.data.dataList : []; if ($scope.data_album_list.length <= 0 && $scope._use_callback) { $scope.buildDummyByType('gallery_id'); } } $scope.data_album_State.load = false; $scope.data_album_State.done = true; }); }; $scope.fetchTimes = 1; /* Get photo list inside (gallery id => album id) */ $scope.data_photo_State = { load: true, done: false }; $scope.data_photo_list = []; $scope.data_total_row = 0; $scope.getPhotoListByAlbumId = function(album_id) { var dummyArray = []; $scope.data_photo_State.load = true; $scope.data_photo_State.done = false; var d = { 'cur_page': $scope.fetchTimes, 'per_page': $scope._linitPtoto, //'txt_sortby': 'image_oldest_create', 'txt_sortby': 'image_lastest_create', 'txt_filter_json': JSON.stringify({ "image_group_id_array": [album_id] }) }; GAEAPI.get('image/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_total_row = res.data.total_rows; angular.forEach(res.data.dataList, function(item, key) { dummyArray.push(item); }); if (!$scope.data_photo_list.length) { $scope.data_photo_list = dummyArray; } else { var currentData = $scope.data_photo_list; $scope.data_photo_list = currentData.concat(dummyArray); } if ($scope.data_photo_list.length <= 0 && $scope._use_callback) { $scope.buildDummyByType('photo_list'); } } $scope.data_photo_State.load = false; $scope.data_photo_State.done = true; console.log("image_fettotal :", $scope.data_total_row); console.log("image_fet :", $scope.fetchTimes); console.log("image_dummyArray :", dummyArray); console.log("image_data_photo_list :", $scope.data_photo_list); }); }; $scope.paddingTop = 40; $scope.padding = function() { var id = CUR_THEME.shop_id(); if (id == 643) { $scope.paddingTop = 20; } else if (id == 436) { $scope.paddingTop = 0; } }; $scope.padding(); $scope.loadMore = function() { $scope.fetchTimes++; $scope.getPhotoListByAlbumId($scope._getIdFromUrl($routeParams.view_album_id)); }; $scope.checkPageType = function() { if (typeof $routeParams.view_album_id !== 'undefined' && $routeParams.view_album_id != '' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id !== '') { return 'view_album_id'; } else if (typeof $routeParams.view_album_id === 'undefined' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id != '') { return 'album_id'; } else { return 'gallery'; } }; $scope.pageType = $scope.checkPageType() || ""; switch ($scope.pageType) { case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; default: break; } /* When route change start */ $rootScope.$on('$routeChangeStart', function(event, current, prev) { var elementName = '[data-iddd="' + $scope._key() + '"]'; var slickIntance = $(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider') || false; if (slickIntance && $scope.type === 'portfolio-carousel-boxed') { $(elementName).slick('unslick'); $scope._uniqueKey = ''; } }); /* When route change */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.pageType = $scope.checkPageType(); switch ($scope.pageType) { case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; } }); /* Currnet Params */ $scope.viewRouteParams = function() { return $routeParams; }; /* Check if seo website */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Build String title url */ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.checkUrlActive = function(activeString) { return (window.location.href.indexOf(activeString) != -1) ? true : false; }; /* Broadcase event -> do something */ $rootScope.$on('repeatend', function() { if ($scope.pageType === 'view_album_id') { /* Check Lightbox Enable/Disable */ $('a[data-photo-index]').each(function(idx, obj) { if ($scope._use_lightBox) { $(this).attr('data-lightbox', 'view-gallery'); } else { $(this).attr('target', '_blank'); $(this).attr('data-nolightbox', 'true'); $(this).removeAttr('data-lightbox'); } }); } if ($scope.type === 'portfolio-carousel-boxed' && $scope.pageType == 'view_album_id') { $('.animateSlideFromRight').each(function(i, object) { if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function() { $(this).addClass('animateEnded').dequeue(); }); } }); return; } else if ($scope.type === 'portfolio-images-boxed') { $('.animteZoomToNormal').each(function(i, object) { if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function() { $(this).addClass('animateEnded').dequeue(); }); } }); return; } if ($('[data-iddd="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.slideInit(); }, 500); } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function() { var elementName = '[data-iddd="' + $scope._key() + '"]'; var optionsParmas = { autoplay: false, slidesToShow: 3, slidesToScroll: 3, dots: true, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [{ breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } }]; var extraOptions = { animate: false, slideFromRight: true, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } setTimeout(function() { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } }); }; $scope.getGridItemWidth = function() { return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx) { if ($scope._use_lightBox) { $('a[data-index="' + idx + '"]').attr('data-lightbox', 'gallery-view'); } else { $('a[data-index="' + idx + '"]').attr('data-nolightbox', 'yes'); } }; $scope._viewRouteParams = function() { return $routeParams; }; $scope._displayCode = function(Strdata) { var b = ""; if (Strdata.indexOf("-")) { var a = Strdata.split("-"); for (var i = 1; i <= a.length; i++) { if (a[i] != "" && a[i] != undefined) { b += " " + a[i]; } } } return b; }; $scope.streamLightbox = function(url, name) { return $streamLightbox(url, name); }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.setdispay = function(imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow', 'hidden'); } $scope.setdispayclose = function(imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow', 'visible'); } $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } }; return promise; });_ui_share_app.directive('componentGalleryAlbumA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentGalleryAlbumA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { type: '@type', imgpath: '@imgpath', uselightbox: '@uselightbox', callback: '@callback', menu: '@menu', size: '@size', maxresult: '@maxresult' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; $scope._use_callback = (typeof $scope.callback !== 'undefined' && $scope.callback !== '') ? true : false; $scope._no_menu = (typeof $scope.menu !== 'undefined' && $scope.menu !== '') ? false : true; $scope._page = 30; if ($scope.maxresult != 'undefined' && $scope.maxresult != '') { $scope._maxresult = $scope.maxresult; } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._getIdFromUrl = function(rawRouteParams) { var a = rawRouteParams; var b = a.split("-"); if (b.length > 0 && a.indexOf("-") !== -1) { return b[0]; } else { return a; } }; /* Build dummy data by gallery type * @params {typeName} type of page * @return array */ $scope.buildDummyByType = function(typeName) { switch (typeName) { case 'gallery': var d = []; for (var i = 0; i < 6; i++) { var item = { 'gallery_badge': [{ badge_id: 18 }], 'gallery_id': (i + 1), 'gallery_name': 'Gallery ' + (i + 1), 'gallery_image': [{ 'image_url': 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }] }; d.push(item); } $scope.data_gallery_list = d; $scope.data_gallery_list_done = true; break; case 'gallery_id': var d = []; for (var i = 0; i < 6; i++) { var item = { 'gallery_badge': [{ badge_id: 18 }], 'image_group_id': 10 + (i + 1), 'image_group_name': 'Album list number ' + (i + 1), 'image_group_image': [{ 'image_url': 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }] }; d.push(item); } $scope.data_album_list = d; break; case 'photo_list': var d = []; for (var i = 0; i < 6; i++) { var item = { 'image_url': 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif', }; d.push(item); } $scope.data_photo_list = d; break; } }; /* Get all gellery for first time*/ $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; $scope.galleryInit = function() { $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; var d = { 'cur_page': 1, 'per_page': $scope._maxresult, 'txt_filter_json': JSON.stringify({ "badge_id_array": [18] }) }; GAEAPI.get('gallery/lists', d, $scope).then(function(e) { $scope.data_gallery_list = (e.ok == 1) ? e.data.dataList : []; $scope.data_gallery_list_done = true; if ($scope.data_gallery_list.length <= 0 && $scope._use_callback) { $scope.buildDummyByType('gallery'); } }); }; $scope.galleryInit(); /* Get album list inside gallery id */ $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(gallery_id) { $scope.data_album_list = []; var d = { 'cur_page': 1, 'per_page': 32, 'txt_filter_json': JSON.stringify({ "gallery_id_array": [gallery_id] }) }; GAEAPI.get('image_group/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_album_list = (res.ok == 1) ? res.data.dataList : []; if ($scope.data_album_list.length <= 0 && $scope._use_callback) { $scope.buildDummyByType('gallery_id'); } } }); }; /* Get photo list inside (gallery id => album id) */ $scope.data_photo_list = []; $scope.getPhotoListByAlbumId = function(album_id) { $scope.data_photo_list = []; var d = { 'cur_page': 1, 'per_page': 50, 'txt_filter_json': JSON.stringify({ "image_group_id_array": [album_id] }) }; GAEAPI.get('image/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_photo_list = (res.ok == 1) ? res.data.dataList : []; if ($scope.data_photo_list.length <= 0 && $scope._use_callback) { $scope.buildDummyByType('photo_list'); } } }); }; $scope.checkPageType = function() { if (typeof $routeParams.view_album_id !== 'undefined' && $routeParams.view_album_id != '' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id !== '') { return 'view_album_id'; } else if (typeof $routeParams.view_album_id === 'undefined' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id != '') { return 'album_id'; } else { return 'gallery'; } }; $scope.pageType = $scope.checkPageType() || ""; switch ($scope.pageType) { case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; default: break; } /* When route change start */ $rootScope.$on('$routeChangeStart', function(event, current, prev) { var elementName = '[data-iddd="' + $scope._key() + '"]'; var slickIntance = $(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider') || false; if (slickIntance && $scope.type === 'portfolio-carousel-boxed') { $(elementName).slick('unslick'); $scope._uniqueKey = ''; } }); /* When route change */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.pageType = $scope.checkPageType(); switch ($scope.pageType) { case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; } }); /* Currnet Params */ $scope.viewRouteParams = function() { return $routeParams; }; /* Check if seo website */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Build String title url */ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.checkUrlActive = function(activeString) { return (window.location.href.indexOf(activeString) != -1) ? true : false; }; /* Broadcase event -> do something */ $rootScope.$on('repeatend', function() { if ($scope.pageType === 'view_album_id') { /* Check Lightbox Enable/Disable */ $('a[data-photo-index]').each(function(idx, obj) { if ($scope._use_lightBox) { $(this).attr('data-lightbox', 'view-gallery'); } else { $(this).attr('target', '_blank'); $(this).attr('data-nolightbox', 'true'); $(this).removeAttr('data-lightbox'); } }); } if ($scope.type === 'portfolio-carousel-boxed' && $scope.pageType == 'view_album_id') { $('.animateSlideFromRight').each(function(i, object) { if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function() { $(this).addClass('animateEnded').dequeue(); }); } }); return; } else if ($scope.type === 'portfolio-images-boxed') { $('.animteZoomToNormal').each(function(i, object) { if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function() { $(this).addClass('animateEnded').dequeue(); }); } }); return; } if ($('[data-iddd="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.slideInit(); }, 500); } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function() { var elementName = '[data-iddd="' + $scope._key() + '"]'; var optionsParmas = { autoplay: false, slidesToShow: 3, slidesToScroll: 3, dots: true, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [{ breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } }]; var extraOptions = { animate: false, slideFromRight: true, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } setTimeout(function() { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } }); }; $scope.getGridItemWidth = function() { return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx) { if ($scope._use_lightBox) { $('a[data-index="' + idx + '"]').attr('data-lightbox', 'gallery-view'); } else { $('a[data-index="' + idx + '"]').attr('data-nolightbox', 'yes'); } }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; }; return promise; }); _ui_share_app.directive('componentGalleryAlbumB', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentGalleryAlbumB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { type: '@type', imgpath: '@imgpath', uselightbox: '@uselightbox', callback: '@callback', menu: '@menu', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; $scope._use_callback = (typeof $scope.callback !== 'undefined' && $scope.callback !== '') ? true : false; $scope._no_menu = (typeof $scope.menu !== 'undefined' && $scope.menu !== '') ? false : true; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._getIdFromUrl = function(rawRouteParams){ var a = rawRouteParams; var b = a.split("-"); if(b.length > 0 && a.indexOf("-") !== -1){ return b[0]; } else { return a; } }; /* Build dummy data by gallery type * @params {typeName} type of page * @return array */ $scope.buildDummyByType = function(typeName){ switch(typeName){ case 'gallery': var d = []; for(var i = 0; i < 6; i++){ var item = { 'gallery_badge': [{badge_id:18}], 'gallery_id': (i+1), 'gallery_name': 'Gallery ' + (i+1), 'gallery_image': [{'image_url':'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}] }; d.push(item); } $scope.data_gallery_list = d; $scope.data_gallery_list_done = true; break; case 'gallery_id': var d = []; for(var i = 0; i < 6; i++){ var item = { 'gallery_badge': [{badge_id:18}], 'image_group_id': 10+(i+1), 'image_group_name': 'Album list number ' + (i+1), 'image_group_image': [{'image_url':'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}] }; d.push(item); } $scope.data_album_list = d; break; case 'photo_list': var d = []; for(var i = 0; i < 6; i++){ var item = { 'image_url':'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif', }; d.push(item); } $scope.data_photo_list = d; break; } }; /* Get all gellery for first time*/ $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; $scope.galleryInit = function(){ $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; var d = { 'cur_page':1, 'per_page':30, 'txt_filter_json': JSON.stringify({"badge_id_array":[18]}) }; GAEAPI.get('gallery/lists',d,$scope).then(function(e){ $scope.data_gallery_list = (e.ok == 1) ? e.data.dataList : []; $scope.data_gallery_list_done = true; if($scope.data_gallery_list.length <= 0 && $scope._use_callback){ $scope.buildDummyByType('gallery'); } }); }; $scope.galleryInit(); /* Get album list inside gallery id */ $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(gallery_id){ $scope.data_album_list = []; var d = { 'cur_page':1, 'per_page':32, 'txt_filter_json': JSON.stringify({"gallery_id_array":[gallery_id]}) }; GAEAPI.get('image_group/lists',d,$scope).then(function(res){ if(res.ok == 1){ $scope.data_album_list = (res.ok == 1) ? res.data.dataList : []; if($scope.data_album_list.length <= 0 && $scope._use_callback){ $scope.buildDummyByType('gallery_id'); } } }); }; /* Get photo list inside (gallery id => album id) */ $scope.data_photo_list = []; $scope.getPhotoListByAlbumId = function(album_id){ $scope.data_photo_list = []; var d = { 'cur_page':1, 'per_page':50, 'txt_filter_json': JSON.stringify({"image_group_id_array":[album_id]}) }; GAEAPI.get('image/lists',d,$scope).then(function(res){ if(res.ok == 1){ $scope.data_photo_list = (res.ok == 1) ? res.data.dataList : []; if($scope.data_photo_list.length <= 0 && $scope._use_callback){ $scope.buildDummyByType('photo_list'); } } }); }; $scope.checkPageType = function(){ if(typeof $routeParams.view_album_id !== 'undefined' && $routeParams.view_album_id != '' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id !== ''){ return 'view_album_id'; } else if(typeof $routeParams.view_album_id === 'undefined' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id != ''){ return 'album_id'; } else { return 'gallery'; } }; $scope.pageType = $scope.checkPageType() || ""; switch($scope.pageType){ case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; default: break; } /* When route change start */ $rootScope.$on('$routeChangeStart', function (event, current, prev) { var elementName = '[data-iddd="'+$scope._key()+'"]'; var slickIntance = $(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider') || false; if (slickIntance && $scope.type === 'portfolio-carousel-boxed') { $(elementName).slick('unslick'); $scope._uniqueKey = ''; } }); /* When route change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { $scope.pageType = $scope.checkPageType(); switch($scope.pageType){ case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; } }); /* Currnet Params */ $scope.viewRouteParams = function(){ return $routeParams; }; /* Check if seo website */ $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Build String title url */ $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; $scope.checkUrlActive = function(activeString){ return (window.location.href.indexOf(activeString) != -1) ? true : false; }; /* Broadcase event -> do something */ $rootScope.$on('repeatend', function() { if($scope.pageType === 'view_album_id'){ /* Check Lightbox Enable/Disable */ $('a[data-photo-index]').each(function(idx,obj){ if($scope._use_lightBox){ $(this).attr('data-lightbox','view-gallery'); } else { $(this).attr('target','_blank'); $(this).attr('data-nolightbox','true'); $(this).removeAttr('data-lightbox'); } }); } if($scope.type === 'portfolio-carousel-boxed' && $scope.pageType == 'view_album_id'){ $('.animateSlideFromRight').each(function(i, object){ if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function () { $(this).addClass('animateEnded').dequeue(); }); } }); return; } else if($scope.type ==='portfolio-images-boxed'){ $('.animteZoomToNormal').each(function(i, object){ if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function () { $(this).addClass('animateEnded').dequeue(); }); } }); return; } if($('[data-iddd="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.slideInit(); }, 500); } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function(){ var elementName = '[data-iddd="'+$scope._key()+'"]'; var optionsParmas = { autoplay: false, slidesToShow: 3, slidesToScroll: 3, dots: true, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false, slideFromRight: true, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } }); }; $scope.getGridItemWidth = function(){ return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx){ if($scope._use_lightBox){ $('a[data-index="'+idx+'"]').attr('data-lightbox','gallery-view'); } else { $('a[data-index="'+idx+'"]').attr('data-nolightbox','yes'); } }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; }; return promise; }); _ui_share_app.directive('componentGalleryAlbumC', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentGalleryAlbumC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { type: '@type', imgpath: '@imgpath', uselightbox: '@uselightbox', callback: '@callback', menu: '@menu', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; $scope._use_callback = (typeof $scope.callback !== 'undefined' && $scope.callback !== '') ? true : false; $scope._no_menu = (typeof $scope.menu !== 'undefined' && $scope.menu !== '') ? false : true; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._getIdFromUrl = function(rawRouteParams){ var a = rawRouteParams; var b = a.split("-"); if(b.length > 0 && a.indexOf("-") !== -1){ return b[0]; } else { return a; } }; /* Build dummy data by gallery type * @params {typeName} type of page * @return array */ $scope.buildDummyByType = function(typeName){ switch(typeName){ case 'gallery': var d = []; for(var i = 0; i < 6; i++){ var item = { 'gallery_badge': [{badge_id:18}], 'gallery_id': (i+1), 'gallery_name': 'Gallery ' + (i+1), 'gallery_image': [{'image_url':'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}] }; d.push(item); } $scope.data_gallery_list = d; $scope.data_gallery_list_done = true; break; case 'gallery_id': var d = []; for(var i = 0; i < 6; i++){ var item = { 'gallery_badge': [{badge_id:18}], 'image_group_id': 10+(i+1), 'image_group_name': 'Album list number ' + (i+1), 'image_group_image': [{'image_url':'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}] }; d.push(item); } $scope.data_album_list = d; break; case 'photo_list': var d = []; for(var i = 0; i < 6; i++){ var item = { 'image_url':'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif', }; d.push(item); } $scope.data_photo_list = d; break; } }; /* Get all gellery for first time*/ $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; $scope.galleryInit = function(){ $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; var d = { 'cur_page':1, 'per_page':30, 'txt_filter_json': JSON.stringify({"badge_id_array":[18]}) }; GAEAPI.get('gallery/lists',d,$scope).then(function(e){ $scope.data_gallery_list = (e.ok == 1) ? e.data.dataList : []; $scope.data_gallery_list_done = true; if($scope.data_gallery_list.length <= 0 && $scope._use_callback){ $scope.buildDummyByType('gallery'); } }); }; $scope.galleryInit(); /* Get album list inside gallery id */ $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(gallery_id){ $scope.data_album_list = []; var d = { 'cur_page':1, 'per_page':32, 'txt_filter_json': JSON.stringify({"gallery_id_array":[gallery_id]}) }; GAEAPI.get('image_group/lists',d,$scope).then(function(res){ if(res.ok == 1){ $scope.data_album_list = (res.ok == 1) ? res.data.dataList : []; if($scope.data_album_list.length <= 0 && $scope._use_callback){ $scope.buildDummyByType('gallery_id'); } } }); }; /* Get photo list inside (gallery id => album id) */ $scope.data_photo_list = []; $scope.getPhotoListByAlbumId = function(album_id){ $scope.data_photo_list = []; var d = { 'cur_page':1, 'per_page':50, 'txt_filter_json': JSON.stringify({"image_group_id_array":[album_id]}) }; GAEAPI.get('image/lists',d,$scope).then(function(res){ if(res.ok == 1){ $scope.data_photo_list = (res.ok == 1) ? res.data.dataList : []; if($scope.data_photo_list.length <= 0 && $scope._use_callback){ $scope.buildDummyByType('photo_list'); } } }); }; $scope.checkPageType = function(){ if(typeof $routeParams.view_album_id !== 'undefined' && $routeParams.view_album_id != '' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id !== ''){ return 'view_album_id'; } else if(typeof $routeParams.view_album_id === 'undefined' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id != ''){ return 'album_id'; } else { return 'gallery'; } }; $scope.pageType = $scope.checkPageType() || ""; switch($scope.pageType){ case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; default: break; } /* When route change start */ $rootScope.$on('$routeChangeStart', function (event, current, prev) { var elementName = '[data-iddd="'+$scope._key()+'"]'; var slickIntance = $(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider') || false; if (slickIntance && $scope.type === 'portfolio-carousel-boxed') { $(elementName).slick('unslick'); $scope._uniqueKey = ''; } }); /* When route change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { $scope.pageType = $scope.checkPageType(); switch($scope.pageType){ case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; } }); /* Currnet Params */ $scope.viewRouteParams = function(){ return $routeParams; }; /* Check if seo website */ $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Build String title url */ $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; $scope.checkUrlActive = function(activeString){ return (window.location.href.indexOf(activeString) != -1) ? true : false; }; /* Broadcase event -> do something */ $rootScope.$on('repeatend', function() { if($scope.pageType === 'view_album_id'){ /* Check Lightbox Enable/Disable */ $('a[data-photo-index]').each(function(idx,obj){ if($scope._use_lightBox){ $(this).attr('data-lightbox','view-gallery'); } else { $(this).attr('target','_blank'); $(this).attr('data-nolightbox','true'); $(this).removeAttr('data-lightbox'); } }); } if($scope.type === 'portfolio-carousel-boxed' && $scope.pageType == 'view_album_id'){ $('.animateSlideFromRight').each(function(i, object){ if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function () { $(this).addClass('animateEnded').dequeue(); }); } }); return; } else if($scope.type ==='portfolio-images-boxed'){ $('.animteZoomToNormal').each(function(i, object){ if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function () { $(this).addClass('animateEnded').dequeue(); }); } }); return; } if($('[data-iddd="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope.slideInit(); }, 500); } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function(){ var elementName = '[data-iddd="'+$scope._key()+'"]'; var optionsParmas = { autoplay: false, slidesToShow: 3, slidesToScroll: 3, dots: true, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false, slideFromRight: true, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } }); }; $scope.getGridItemWidth = function(){ return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx){ if($scope._use_lightBox){ $('a[data-index="'+idx+'"]').attr('data-lightbox','gallery-view'); } else { $('a[data-index="'+idx+'"]').attr('data-nolightbox','yes'); } }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; }; return promise; }); _ui_share_app.directive('componentGalleryAlbumD', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentGalleryAlbumD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', type: '@type', databuttonmore: '@databuttonmore', imgpath: '@imgpath', uselightbox: '@uselightbox', callback: '@callback', menu: '@menu', setall: '@setall', linitPtoto: '@linitptoto', fontcolor: '@fontcolor', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.setall = (typeof $scope.setall !== 'undefined' && $scope.setall !== '') ? $scope.setall : 'All'; $scope._databuttonmore = (typeof $scope.databuttonmore !== 'undefined' && $scope.databuttonmore !== '') ? $scope.databuttonmore : 'filled_button_small_round'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; $scope._use_callback = (typeof $scope.callback !== 'undefined' && $scope.callback !== '') ? true : false; $scope._no_menu = (typeof $scope.menu !== 'undefined' && $scope.menu !== '') ? false : true; $scope._linitPtoto = (typeof $scope.linitPtoto !== 'undefined' && $scope.linitPtoto !== '') ? $scope.linitPtoto : 9; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._getIdFromUrl = function(rawRouteParams) { var a = rawRouteParams; var b = a.split("-"); if (b.length > 0 && a.indexOf("-") !== -1) { return b[0]; } else { return a; } }; /* Build dummy data by gallery type * @params {typeName} type of page * @return array */ $scope.buildDummyByType = function(typeName) { switch (typeName) { case 'gallery': var d = []; for (var i = 0; i < 6; i++) { var item = { 'gallery_badge': [{ badge_id: 18 }], 'gallery_id': (i + 1), 'gallery_name': 'Gallery ' + (i + 1), 'gallery_image': [{ 'image_url': 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }] }; d.push(item); } $scope.data_gallery_list = d; $scope.data_gallery_list_done = true; break; case 'gallery_id': var d = []; for (var i = 0; i < 6; i++) { var item = { 'gallery_badge': [{ badge_id: 18 }], 'image_group_id': 10 + (i + 1), 'image_group_name': 'Album list number ' + (i + 1), 'image_group_image': [{ 'image_url': 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }] }; d.push(item); } $scope.data_album_list = d; break; case 'photo_list': var d = []; for (var i = 0; i < 6; i++) { var item = { 'image_url': 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif', }; d.push(item); } $scope.data_photo_list = d; break; } }; /* Get all gellery for first time*/ $scope.data_gallery_State = { load: true, done: false }; $scope.data_gallery_list = []; $scope.data_gallery_list_done = false; $scope.galleryInit = function() { $scope.data_gallery_list = []; $scope.data_gallery_State.load = true; $scope.data_gallery_State.done = false; $scope.data_gallery_list_done = false; var d = { 'cur_page': 1, 'per_page': 30, 'txt_filter_json': JSON.stringify({ "badge_id_array": [18] }) }; GAEAPI.get('gallery/lists', d, $scope).then(function(e) { $scope.data_gallery_list = (e.ok == 1) ? e.data.dataList : []; $scope.data_gallery_list_done = true; if ($scope.data_gallery_list.length <= 0 && $scope._use_callback) { $scope.buildDummyByType('gallery'); } $scope.data_gallery_State.load = false; $scope.data_gallery_State.done = true; }); }; $scope.galleryInit(); /* Get album list inside gallery id */ $scope.data_album_State = { load: true, done: false }; $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(gallery_id) { $scope.data_album_list = []; $scope.data_album_State.load = true; $scope.data_album_State.done = false; var d = { 'cur_page': 1, 'per_page': 32, 'txt_sortby': 'image_group_sort_index_ASC', 'txt_filter_json': JSON.stringify({ "gallery_id_array": [gallery_id] }) }; GAEAPI.get('image_group/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_album_list = (res.ok == 1) ? res.data.dataList : []; if ($scope.data_album_list.length <= 0 && $scope._use_callback) { $scope.buildDummyByType('gallery_id'); } } $scope.data_album_State.load = false; $scope.data_album_State.done = true; }); }; $scope.fetchTimes = 1; /* Get photo list inside (gallery id => album id) */ $scope.data_photo_State = { load: true, done: false }; $scope.data_photo_list = []; $scope.data_total_row = 0; $scope.getPhotoListByAlbumId = function(album_id) { var dummyArray = []; $scope.data_photo_State.load = true; $scope.data_photo_State.done = false; var d = { 'cur_page': $scope.fetchTimes, 'per_page': $scope._linitPtoto, //'txt_sortby': 'image_oldest_create', 'txt_sortby': 'image_lastest_create', 'txt_filter_json': JSON.stringify({ "image_group_id_array": [album_id] }) }; GAEAPI.get('image/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_total_row = res.data.total_rows; angular.forEach(res.data.dataList, function(item, key) { dummyArray.push(item); }); if (!$scope.data_photo_list.length) { $scope.data_photo_list = dummyArray; } else { var currentData = $scope.data_photo_list; $scope.data_photo_list = currentData.concat(dummyArray); } if ($scope.data_photo_list.length <= 0 && $scope._use_callback) { $scope.buildDummyByType('photo_list'); } } $scope.data_photo_State.load = false; $scope.data_photo_State.done = true; console.log("image_fettotal :", $scope.data_total_row); console.log("image_fet :", $scope.fetchTimes); console.log("image_dummyArray :", dummyArray); console.log("image_data_photo_list :", $scope.data_photo_list); }); }; $scope.paddingTop = 40; $scope.padding = function() { var id = CUR_THEME.shop_id(); if (id == 643) { $scope.paddingTop = 20; } }; $scope.padding(); $scope.loadMore = function() { $scope.fetchTimes++; $scope.getPhotoListByAlbumId($scope._getIdFromUrl($routeParams.view_album_id)); }; $scope.checkPageType = function() { if (typeof $routeParams.view_album_id !== 'undefined' && $routeParams.view_album_id != '' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id !== '') { return 'view_album_id'; } else if (typeof $routeParams.view_album_id === 'undefined' && typeof $routeParams.album_id !== 'undefined' && $routeParams.album_id != '') { return 'album_id'; } else { return 'gallery'; } }; $scope.pageType = $scope.checkPageType() || ""; switch ($scope.pageType) { case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; default: break; } /* When route change start */ $rootScope.$on('$routeChangeStart', function(event, current, prev) { var elementName = '[data-iddd="' + $scope._key() + '"]'; var slickIntance = $(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider') || false; if (slickIntance && $scope.type === 'portfolio-carousel-boxed') { $(elementName).slick('unslick'); $scope._uniqueKey = ''; } }); /* When route change */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.pageType = $scope.checkPageType(); switch ($scope.pageType) { case 'album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); $scope.getAlbumListByGalleryId(gallery_id); break; case 'view_album_id': var gallery_id = $scope._getIdFromUrl($routeParams.album_id); var album_id = $scope._getIdFromUrl($routeParams.view_album_id); $scope.getAlbumListByGalleryId(gallery_id); $scope.getPhotoListByAlbumId(album_id); break; } }); /* Currnet Params */ $scope.viewRouteParams = function() { return $routeParams; }; /* Check if seo website */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Build String title url */ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.checkUrlActive = function(activeString) { return (window.location.href.indexOf(activeString) != -1) ? true : false; }; /* Broadcase event -> do something */ $rootScope.$on('repeatend', function() { if ($scope.pageType === 'view_album_id') { /* Check Lightbox Enable/Disable */ $('a[data-photo-index]').each(function(idx, obj) { if ($scope._use_lightBox) { $(this).attr('data-lightbox', 'view-gallery'); } else { $(this).attr('target', '_blank'); $(this).attr('data-nolightbox', 'true'); $(this).removeAttr('data-lightbox'); } }); } if ($scope.type === 'portfolio-carousel-boxed' && $scope.pageType == 'view_album_id') { $('.animateSlideFromRight').each(function(i, object) { if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function() { $(this).addClass('animateEnded').dequeue(); }); } }); return; } else if ($scope.type === 'portfolio-images-boxed') { $('.animteZoomToNormal').each(function(i, object) { if (!$(this).hasClass('animateEnded')) { $(this).delay(350 * (i + 1)).queue(function() { $(this).addClass('animateEnded').dequeue(); }); } }); return; } if ($('[data-iddd="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.slideInit(); }, 500); } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function() { var elementName = '[data-iddd="' + $scope._key() + '"]'; var optionsParmas = { autoplay: false, slidesToShow: 3, slidesToScroll: 3, dots: true, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [{ breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } }]; var extraOptions = { animate: false, slideFromRight: true, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } setTimeout(function() { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } }); }; $scope.getGridItemWidth = function() { return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx) { if ($scope._use_lightBox) { $('a[data-index="' + idx + '"]').attr('data-lightbox', 'gallery-view'); } else { $('a[data-index="' + idx + '"]').attr('data-nolightbox', 'yes'); } }; $scope._viewRouteParams = function() { return $routeParams; }; $scope._displayCode = function(Strdata) { var b = ""; if (Strdata.indexOf("-")) { var a = Strdata.split("-"); for (var i = 1; i <= a.length; i++) { if (a[i] != "" && a[i] != undefined) { b += " " + a[i]; } } } return b; }; $scope.streamLightbox = function(url, name) { return $streamLightbox(url, name); }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.setdispay = function(imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow', 'hidden'); } $scope.setdispayclose = function(imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow', 'visible'); } $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } }; return promise; });_ui_share_app.directive('componentGalleryId', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentGalleryId'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { galleryid: '@galleryid', galleryname: '@galleryname', uselightbox: '@uselightbox', type: '@type', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Get album list inside gallery id */ $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, imageUrl: function(size, image_url) { var url = image_url.split("/"), length_url = url[url.length - 1]; url[url.length - 1] = size + '_' + length_url; return url.join("/"); }, resizeImageUrl: function(output, callback) { var _self = this; for (var i = 0; i <= output.length; i++) { if (i < output.length) { if (output[i].image_group_image.length != 0) { output[i].image_group_image[0].image_url = _self.imageUrl('t300', output[i].image_group_image[0].image_url); } } else { callback(output); } } }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; _self.getRouteParams(function(params) { var filter_json = { "gallery_id_array": [$scope.galleryid] }; var dataSend = { 'cur_page': 1, 'per_page': 50, 'txt_filter_json': JSON.stringify(filter_json) }; _self.dataSend('image_group/lists', dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.consoleLog("getApi : output : ", output); _self.resizeImageUrl(output.data.dataList, function(dataList) { $scope.dataArray = dataList; }); }); }); }); } } return getFunction; }; $scope.getData().main(); /* $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(gallery_id) { $scope.data_album_list = []; var d = { 'cur_page': 1, 'per_page': 32, 'txt_filter_json': JSON.stringify({ "gallery_id_array": [gallery_id] }) }; GAEAPI.get('image_group/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_album_list = (res.ok == 1) ? res.data.dataList : []; } console.log("getAlbumListByGalleryId", res); }); }; $scope.getAlbumListByGalleryId($scope.galleryid); */ /* When route change */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) {}); /* Currnet Params */ $scope.viewRouteParams = function() { return $routeParams; }; /* Check if seo website */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Build String title url */ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.checkUrlActive = function(activeString) { return (window.location.href.indexOf(activeString) != -1) ? true : false; }; /* Broadcase event -> do something */ $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-unique="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.slideInit(); }, 500); } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function() { var elementName = '.component_carousel_map[data-unique="' + $scope._key() + '"]'; var optionsParmas = { autoplay: false, slidesToShow: 4, slidesToScroll: 2, dots: false, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [{ breakpoint: 1240, settings: { slidesToShow: 4, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 1000, settings: { slidesToShow: 3, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 3, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 630, settings: { slidesToShow: 2, slidesToScroll: 1, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } }]; var extraOptions = { animate: false, slideFromRight: false, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); /*angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } });*/ }; $scope.getGridItemWidth = function() { return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx) { if ($scope._use_lightBox) { $('a[data-index="' + idx + '"]').attr('data-lightbox', 'gallery-view'); } else { $('a[data-index="' + idx + '"]').attr('data-nolightbox', 'yes'); } }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; }; return promise; });_ui_share_app.directive('componentGalleryIdTypeB', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentGalleryIdTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { galleryid: '@galleryid', galleryname: '@galleryname', uselightbox: '@uselightbox', type: '@type', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope._use_lightBox = (typeof $scope.uselightbox !== 'undefined' && $scope.uselightbox !== '') ? true : false; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.data_gal_list = false; $scope.getgalId = function() { $scope.data_photo_list = []; var d = { 'txt_gallery_id': $scope.galleryid }; GAEAPI.get('gallery/id', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_gal_list = (res.ok == 1) ? res.data : []; } }); }; $scope.getgalId(); /* Get photo list inside (gallery id => album id) */ $scope.data_photo_list = []; $scope.getPhotoListByAlbumId = function(gallery_id) { $scope.data_photo_list = []; var d = { 'cur_page': 1, 'per_page': 50, 'txt_filter_json': JSON.stringify({ "image_group_id_array": [album_id] }) }; GAEAPI.get('image/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_photo_list = (res.ok == 1) ? res.data.dataList : []; } }); }; /* Get album list inside gallery id */ $scope.data_album_list = []; $scope.getAlbumListByGalleryId = function(gallery_id) { $scope.data_album_list = []; var d = { 'cur_page': 1, 'per_page': 32, 'txt_filter_json': JSON.stringify({ "gallery_id_array": [gallery_id] }) }; GAEAPI.get('image_group/lists', d, $scope).then(function(res) { if (res.ok == 1) { $scope.data_album_list = (res.ok == 1) ? res.data.dataList : []; } console.log("getAlbumListByGalleryId", res); }); }; $scope.getAlbumListByGalleryId($scope.galleryid); /* When route change */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) {}); /* Currnet Params */ $scope.viewRouteParams = function() { return $routeParams; }; /* Check if seo website */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Build String title url */ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.checkUrlActive = function(activeString) { return (window.location.href.indexOf(activeString) != -1) ? true : false; }; /* Broadcase event -> do something */ $rootScope.$on('repeatend', function() { // if ($('.component_carousel_map[data-unique="' + $scope._key() + '"]').not('.slick-initialized')) { // $timeout(function() { // $scope.slideInit(); // }, 500); // } }); /* Carousel */ $scope.prev_win_size = $(window).width(); $scope.slideInit = function() { var elementName = '.component_carousel_map[data-unique="' + $scope._key() + '"]'; var optionsParmas = { autoplay: true, slidesToShow: 3, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: false, variableWidth: false }; optionsParmas.responsive = [{ breakpoint: 1240, settings: { slidesToShow: 3, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 1000, settings: { slidesToShow: 3, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 3, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 630, settings: { slidesToShow: 2, slidesToScroll: 1, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } }]; var extraOptions = { animate: false, slideFromRight: false, }; sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); console.log("repeatend: Option", optionsParmas); /*angular.element($window).bind('resize',function(){ if($scope.prev_win_size != $(window).width()){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } setTimeout(function(){ if($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')){ $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, "", $scope._key(), extraOptions); }, 3000); } });*/ }; $scope.getGridItemWidth = function() { return (angular.element('.col-item').eq(0).width() - 150) / 2; }; $scope.checkLightbox = function(idx) { if ($scope._use_lightBox) { $('a[data-index="' + idx + '"]').attr('data-lightbox', 'gallery-view'); } else { $('a[data-index="' + idx + '"]').attr('data-nolightbox', 'yes'); } }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; }; return promise; }); _ui_share_app.directive('componentGridBrand', function ($rootScope, $routeParams) { var templateName = 'componentGridBrand'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.brandArray = []; $scope.getData = function(){ var d = {'txt_referral_type_id':12,'txt_sortby':'referral_name_a-z'}; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok==1){ $scope.brandArray = e.data; } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentGridCategory', function ($rootScope, $routeParams) { var templateName = 'componentGridCategory'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', imgpath: '@imgpath', shopname: '@shopname', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ var d = {'txt_referral_type_id':11,'txt_sortby':'referral_name_a-z'}; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentGridCategoryAb', function($rootScope, $routeParams) { var templateName = 'componentGridCategoryAb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = "componentGridCategoryAb"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { console.log($scope._component, ' : ', functionName, ' : ', data); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, main: function() { var _self = this; } } return getFunction; }; /* category */ $scope.setData = { dataSend: { txt_referral_type_id: 11, txt_sortby: 'referral_sort_index_asc_name_asc', txt_filter_json: [] }, api: "referral/map", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }; /* category */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.setData.dataArrayState = res_state; var txt_filter_json = { "badge_id_array": [16, 18] }; $scope.setData.dataSend.txt_filter_json = JSON.stringify(txt_filter_json); $scope.getData().dataSend($scope.setData.api, $scope.setData.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api, res_state) { $scope.setData.ok = res_ok; $scope.setData.dataArray = get_res_api.data; $scope.setData.dataArrayState = res_state; }); }); }); }; return promise; }); _ui_share_app.directive('componentGridCategoryB', function ($rootScope, $routeParams) { var templateName = 'componentGridCategoryB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ var txt_filter_json = { 'badge_id_array':[16] }; var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_name_a-z', }; GAEAPI.get('referral/map',d).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; console.log("testetydshdgshd : "+$scope.categoryArray); } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentGridCategoryC', function ($rootScope, $routeParams) { var templateName = 'componentGridCategoryC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', imgpath: '@imgpath', shopname: '@shopname', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_name_a-z' }; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; } }); }; $scope.getData(); /* When Click */ $scope.viewLink = function(itemObject){ var page = "category-lists"; if($scope.checkSeo()){ page = "#/category-lists"; } window.location.href = page+"?referral_id="+itemObject.referral_id+"&root_id="+itemObject.referral_id+"&referral_name="+itemObject.referral_name+"&referral_type=category"; }; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentGridCategoryD', function ($rootScope, $routeParams) { var templateName = 'componentGridCategoryD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ var txt_filter_json = { 'badge_id_array':[16] }; var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_name_a-z', 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('referral/map',d).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; console.log("testetydshdgshd : "+$scope.categoryArray); } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentGridCategoryDb', function ($rootScope, $routeParams) { var templateName = 'componentGridCategoryDb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { text: '@text', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ var txt_filter_json = { 'badge_id_array':[16] }; var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_name_a-z', 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('referral/map',d).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; console.log("categoryArray : "+$scope.categoryArray); } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentGridCategoryE', function ($rootScope, $routeParams) { var templateName = 'componentGridCategoryE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', imgpath: '@imgpath', name: '@name', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ var txt_filter_json = { 'badge_id_array':[16] }; var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_name_a-z', }; GAEAPI.get('referral/map',d).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; console.log("testetydshdgshd : "+$scope.categoryArray); } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentGridCategoryF', function ($rootScope, $routeParams) { var templateName = 'componentGridCategoryF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { text: '@text', name:'@neme', refid:'@refid', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function() { var txt_filter_json = { 'badge_id_array':[18] }; if(typeof $scope.refid !== 'undefined'){ var d = { 'txt_referral_type_id':11, 'txt_parent_id': $scope.refid, 'txt_sortby':'referral_oldest_create', }; } else { var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_oldest_create', }; } GAEAPI.get('referral/map',d).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; console.log("categoryArray : ",$scope.categoryArray); } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentGridCategoryG', function ($rootScope, $routeParams) { var templateName = 'componentGridCategoryG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { text: '@text', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ var txt_filter_json = { 'badge_id_array':[18] }; var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_oldest_create', /* 'txt_filter_json': JSON.stringify(txt_filter_json) */ }; GAEAPI.get('referral/map',d).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; console.log("categoryArray : "+$scope.categoryArray); } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentGridCategoryH', function ($rootScope, $routeParams) { var templateName = 'componentGridCategoryH'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { text: '@text', name:'@neme', refid:'@refid', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ var txt_filter_json = { 'badge_id_array':[18] }; if(typeof $scope.refid !== 'undefined'){ var d = { 'txt_referral_type_id':11, 'txt_parent_id': $scope.refid, 'txt_sortby':'referral_oldest_create' }; }else{ var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_oldest_create', }; } GAEAPI.get('referral/map',d).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; console.log("categoryArray : ",$scope.categoryArray); } }); }; $scope.getData(); }; return promise; }); _ui_share_app.directive('componentGridCategoryI', function ($rootScope, $routeParams) { var templateName = 'componentGridCategoryI'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', imgpath: '@imgpath', shopname: '@shopname', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.categoryArray = []; $scope.getData = function(){ var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_name_a-z' }; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok==1){ $scope.categoryArray = e.data; } }); }; $scope.getData(); /* When Click */ $scope.viewLink = function(itemObject){ var page = "category-lists"; if($scope.checkSeo()){ page = "#/category-lists"; } window.location.href = page+"?referral_id="+itemObject.referral_id+"&root_id="+itemObject.referral_id+"&referral_type=category"; }; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentHeader', function ($rootScope, $routeParams) { var templateName = 'componentHeader'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name :'@name', id:'=', background:'@', primary:'@', secondary:'@', imgpath:'@' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.pixelCheck = 240; /*if(CUR_THEME.shop_id()=="635"){ $scope.pixelCheck = 480; }*/ /* * header mobile event on "scroll" */ angular.element($window).bind('scroll', function(){ if ($(document).scrollTop() > $scope.pixelCheck && $(window).width() >= 931) { if(!angular.element('.desktop_scroll').hasClass('active')){ angular.element('.desktop_scroll').addClass('active'); } } else { if(angular.element('.desktop_scroll').hasClass('active')){ angular.element('.desktop_scroll').removeClass('active'); } } }); /* * header mobile event on "resize" */ angular.element($window).bind('resize', function(){ if($(document).width() >= 992 && angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').removeClass('mobile_open_active'); } }); /* * active mobile menu */ $scope.activeMobileMenu=function(){ $('body').css('overflow','hidden'); if(!angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').addClass('mobile_open_active') } }; /* * unactive mobile menu */ $scope.unactiveMobileMenu=function(){ $('body').css('overflow','auto'); if(angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').removeClass('mobile_open_active'); angular.element('.close').removeClass('active_x'); angular.element('.section').removeClass('active_y'); } }; $scope.goPath = function(t){ window.location.href=t; }; }; return promise; }); _ui_share_app.directive('componentHeaderA', function($rootScope, $routeParams) { var componentMain = 'componentHeader'; var componentChild = 'a'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'menu_search': '?menuSearch', 'menu_user': '?menuUser', 'menu_cart': '?menuCart', 'menu_left': '?menuLeft', 'menu_middle': '?menuMiddle', 'menu_right': '?menuRight', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.unViewMobile = function() { $('body').css('position', 'relative'); }; $scope._getMe = {}; $scope._isLogin = function() { if (UiCustomerBox.delegate.get.isLogin()) { $scope._getMe = UiCustomerBox.delegate.get.me(); } return UiCustomerBox.delegate.get.isLogin(); }; $scope._getLogin = function() { $scope.unactiveMobileMenu(); if (!UiCustomerBox.delegate.get.isLogin()) { return $inloginPopup.open(); } else { UiCustomerBox.delegate.modal.open(); } /* return UiCustomerBox.delegate.modal.openLoginForm(); */ }; $scope._getSearch = function() { $scope.unactiveMobileMenu(); return UiSearchBox.delegate.modal.open(); }; $scope._getInfo = function() { $scope.unactiveMobileMenu(); return UiCustomerBox.delegate.modal.open(); }; $scope._getLogout = function() { $scope.unactiveMobileMenu(); return UiCustomerBox.delegate.doLogOut(); }; $scope._cartPriceTotal = function() { return UiCart.delegate.get.totalPrice() || 0; }; $scope._cartTotal = function() { return UiCart.delegate.get.totalAmount() || 0; }; $scope._modalOpen = function(elementType, enableGuess, skipToCheckout) { /* return UiCart.delegate.modal.open(); */ $scope.unactiveMobileMenu(); return $virtualCartTypeB.isCart(); }; /* * header mobile event on "scroll" */ angular.element($window).bind('scroll', function() { if ($(document).scrollTop() > 50.25 && $(window).width() >= 991) { if (!$('.a_container').hasClass('active')) { $('.a_container').addClass('active'); $('.menu-on-desktop-scroll').addClass('active'); $('.a_container .menu-on-desktop .on-middle img.normal').css('opacity', 0); $timeout(function() { /*$('.a_container .menu-on-desktop .on-middle img.normal').animate({'opacity':0});*/ $timeout(function() { $('.a_container .menu-on-desktop .on-middle img.normal').css('display', 'none'); $('.a_container .menu-on-desktop .on-middle img.onScroll').css({ 'display': 'block' }); $timeout(function() { $('.a_container .menu-on-desktop .on-middle img.onScroll').animate({ 'opacity': 1 }); }, 300); }, 1); }, 300); } } else { if ($('.a_container').hasClass('active')) { $('.a_container').removeClass('active'); $('.menu-on-desktop-scroll').removeClass('active'); $('.a_container .menu-on-desktop .on-middle img.onScroll').css('opacity', 0); $timeout(function() { /*$('.a_container .menu-on-desktop .on-middle img.onScroll').css('opacity',0);*/ $timeout(function() { $('.a_container .menu-on-desktop .on-middle img.onScroll').css('display', 'none'); $('.a_container .menu-on-desktop .on-middle img.normal').css('display', 'block'); $timeout(function() { $('.a_container .menu-on-desktop .on-middle img.normal').animate({ 'opacity': 1 }); }, 300); }, 1); }, 300); } } }); /* * header mobile event on "resize" */ angular.element($window).bind('resize', function() { if ($(document).width() >= 992 && $('.a_container').hasClass('active')) { $('.a_container').removeClass('active'); $('.menu-on-desktop-scroll').removeClass('active'); } }); /* * active mobile menu */ $scope.activeMobileMenu = function() { $('body').css('position', 'fixed'); if (!angular.element('.menu-on-mobile-active').hasClass('active')) { angular.element('.menu-on-mobile-active').addClass('active') } }; /* * unactive mobile menu */ $scope.unactiveMobileMenu = function() { $('body').css('position', 'relative'); if (angular.element('.menu-on-mobile-active').hasClass('active')) { angular.element('.menu-on-mobile-active').removeClass('active'); } }; $scope.goPath = function(t) { window.location.href = t; }; }; return promise; }); _ui_share_app.directive('componentHeaderB', function ($rootScope, $routeParams) { var componentMain = 'componentHeader'; var componentChild = 'b'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild+ '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath:'@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'menu_left':'?menuLeft', 'menu_middle':'?menuMiddle', 'menu_right':'?menuRight', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.unViewMobile = function() { $('body').css('position','relative'); }; $scope._getMe = {}; $scope._isLogin = function() { if (UiCustomerBox.delegate.get.isLogin()) { $scope._getMe = UiCustomerBox.delegate.get.me(); } return UiCustomerBox.delegate.get.isLogin(); }; $scope._getLogin = function() { $scope.unViewMobile(); return UiCustomerBox.delegate.modal.openLoginForm(); }; $scope._getSearch = function() { $scope.unViewMobile(); return UiSearchBox.delegate.modal.open(); }; $scope._getInfo = function() { $scope.unViewMobile(); return UiCustomerBox.delegate.modal.open(); }; $scope._getLogout = function() { $scope.unViewMobile(); return UiCustomerBox.delegate.doLogOut(); }; $scope._cartPriceTotal = function() { return UiCart.delegate.get.totalPrice() || 0; }; $scope._cartTotal = function() { return UiCart.delegate.get.totalAmount() || 0; }; $scope._modalOpen = function(elementType, enableGuess, skipToCheckout) { if (typeof UiCustomerBox === 'undefined' || UiCustomerBox == undefined) { return; } var delayTrigger = 100; $scope.unViewMobile(); var modalOpenTimer = setTimeout(function() { return UiCart.delegate.modal.open(); clearTimeout(modalOpenTimer); if (!UiCustomerBox.delegate.get.isLogin()) { return UiCustomerBox.delegate.modal.openLoginForm(); } else if (UiCustomerBox.delegate.get.isLogin()) { return UiCart.delegate.modal.open(); } }, delayTrigger); }; /* * header mobile event on "scroll" */ angular.element($window).bind('scroll', function(){ if ($(document).scrollTop() > 300 && $(window).width() >= 991) { if(!$('.a_container').hasClass('active')){ $('.a_container').addClass('active'); $('.menu-on-desktop-scroll').addClass('active'); } } else { if($('.a_container').hasClass('active')){ $('.a_container').removeClass('active'); $('.menu-on-desktop-scroll').removeClass('active'); } } }); /* * header mobile event on "resize" */ angular.element($window).bind('resize', function(){ if($(document).width() >= 992 && $('.a_container').hasClass('active')){ $('.a_container').removeClass('active'); $('.menu-on-desktop-scroll').removeClass('active'); } }); /* * active mobile menu */ $scope.activeMobileMenu=function(){ $('body').css('position','fixed'); if(!angular.element('.menu-on-mobile-active').hasClass('active')){ angular.element('.menu-on-mobile-active').addClass('active') } }; /* * unactive mobile menu */ $scope.unactiveMobileMenu=function(){ $('body').css('position','relative'); if(angular.element('.menu-on-mobile-active').hasClass('active')){ angular.element('.menu-on-mobile-active').removeClass('active'); } }; $scope.goPath = function(t){ window.location.href=t; }; }; return promise; }); _ui_share_app.directive('componentHeaderC', function ($rootScope, $routeParams) { var componentMain = 'componentHeader'; var componentChild = 'c'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild+ '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath:'@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'menu_left':'?menuLeft', 'menu_middle':'?menuMiddle', 'menu_right':'?menuRight', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.unViewMobile = function() { $('body').css('position','relative'); }; $scope._getMe = {}; $scope._isLogin = function() { if (UiCustomerBox.delegate.get.isLogin()) { $scope._getMe = UiCustomerBox.delegate.get.me(); } return UiCustomerBox.delegate.get.isLogin(); }; $scope._getLogin = function() { $scope.unViewMobile(); return UiCustomerBox.delegate.modal.openLoginForm(); }; $scope._getSearch = function() { $scope.unViewMobile(); return UiSearchBox.delegate.modal.open(); }; $scope._getInfo = function() { $scope.unViewMobile(); return UiCustomerBox.delegate.modal.open(); }; $scope._getLogout = function() { $scope.unViewMobile(); return UiCustomerBox.delegate.doLogOut(); }; $scope._cartPriceTotal = function() { return UiCart.delegate.get.totalPrice() || 0; }; $scope._cartTotal = function() { return UiCart.delegate.get.totalAmount() || 0; }; $scope._modalOpen = function(elementType, enableGuess, skipToCheckout) { if (typeof UiCustomerBox === 'undefined' || UiCustomerBox == undefined) { return; } var delayTrigger = 100; $scope.unViewMobile(); var modalOpenTimer = setTimeout(function() { return UiCart.delegate.modal.open(); clearTimeout(modalOpenTimer); if (!UiCustomerBox.delegate.get.isLogin()) { return UiCustomerBox.delegate.modal.openLoginForm(); } else if (UiCustomerBox.delegate.get.isLogin()) { return UiCart.delegate.modal.open(); } }, delayTrigger); }; /* * header mobile event on "scroll" */ angular.element($window).bind('scroll', function(){ if ($(document).scrollTop() > 300 ) { $('.menu-on-desktop-scroll').addClass('active'); } else { $('.menu-on-desktop-scroll').removeClass('active'); } }); /* * header mobile event on "resize" */ angular.element($window).bind('resize', function(){ if($(document).width() >= 992 && $('.a_container').hasClass('active')){ $('.a_container').removeClass('active'); $('.menu-on-desktop-scroll').removeClass('active'); } }); /* * active mobile menu */ $scope.activeMobileMenu=function(){ $('body').css('overflow','hidden'); if(!angular.element('.menu-on-mobile-active').hasClass('active')){ angular.element('.menu-on-mobile-active').addClass('active') } }; /* * unactive mobile menu */ $scope.unactiveMobileMenu=function(){ $('body').css('overflow','auto'); $('body').css('position','relative'); if(angular.element('.menu-on-mobile-active').hasClass('active')){ angular.element('.menu-on-mobile-active').removeClass('active'); } }; $scope.goPath = function(t){ window.location.href=t; }; }; return promise; }); _ui_share_app.directive('componentHeaderD', function ($rootScope, $routeParams) { var componentMain = 'componentHeader'; var componentChild = 'd'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'menu_left': '?menuLeft', 'menu_middle': '?menuMiddle', 'menu_right': '?menuRight', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.unViewMobile = function () { $('body').css('position', 'relative'); $scope.unactiveMobileMenu(); }; $scope._getMe = {}; $scope._isLogin = function () { if (UiCustomerBox.delegate.get.isLogin()) { $scope._getMe = UiCustomerBox.delegate.get.me(); } return UiCustomerBox.delegate.get.isLogin(); }; $scope._getLogin = function () { $scope.unViewMobile(); /*return UiCustomerBox.delegate.modal.openLoginForm();*/ return $inloginPopup.open(); }; $scope._getSearch = function () { $scope.unViewMobile(); return UiSearchBox.delegate.modal.open(); }; $scope._getInfo = function () { $scope.unViewMobile(); if ($scope._isLogin() == true) { return UiCustomerBox.delegate.modal.open(); }else { return $inloginPopup.open(); } }; $scope._getLogout = function () { $scope.unViewMobile(); return UiCustomerBox.delegate.doLogOut(); }; $scope._cartPriceTotal = function () { return UiCart.delegate.get.totalPrice() || 0; }; $scope._cartTotal = function () { return UiCart.delegate.get.totalAmount() || 0; }; $scope._modalOpen = function (elementType, enableGuess, skipToCheckout) { UiCart.delegate.modal.open(); }; /* * header mobile event on "scroll" */ angular.element($window).bind('scroll', function () { if ($(document).scrollTop() > 300) { $('.menu-on-desktop-scroll').addClass('active'); } else { $('.menu-on-desktop-scroll').removeClass('active'); } }); /* * header mobile event on "resize" */ angular.element($window).bind('resize', function () { if ($(document).width() >= 992 && $('.a_container').hasClass('active')) { $('.a_container').removeClass('active'); $('.menu-on-desktop-scroll').removeClass('active'); } }); /* * active mobile menu */ $scope.activeMobileMenu = function () { $('body').css('overflow', 'hidden'); if (!angular.element('.menu-on-mobile-active').hasClass('active')) { angular.element('.menu-on-mobile-active').addClass('active') } }; /* * unactive mobile menu */ $scope.unactiveMobileMenu = function () { $('body').css('overflow', 'auto'); $('body').css('position', 'relative'); if (angular.element('.menu-on-mobile-active').hasClass('active')) { angular.element('.menu-on-mobile-active').removeClass('active'); } return mClose(); }; $scope.goPath = function (t) { window.location.href = t; }; $scope.mobileOpen = function () { $('body').css('position', 'fixed'); if (!$('.section-mobile-side').hasClass('active')) { $('.section-mobile-side').addClass('active'); } }; $scope.mobileClose = function () { $('body').css('position', 'relative'); if ($('.section-mobile-side').hasClass('active')) { $('.section-mobile-side').removeClass('active'); } }; $scope.openCart = function () { $scope.mobileClose(); return $virtualCartTypeA.isOpenOrClose(); }; $scope.expandMenuLeft = function (el) { var id = el.getAttribute('data-id'); $('.menu-parent[data-id="' + id + '"]').toggleClass('active'); $('.subMenu[data-id="' + id + '"]').toggleClass('active'); }; /* Get referral data * @return array */ $scope.data_referral = []; $scope.getDataReferral = function(){ var dataSend = { 'txt_referral_type_id': 11 }; GAEAPI.get('referral/map', dataSend).then(function (e) { if (e.ok == 1) { $scope.data_referral = e.data; } }); }; $scope.getDataReferral(); angular.element($window).bind('scroll', function () { if ($(window).scrollTop() >= 344 && $(window).width() >= 992) { /*if(!$('#section-sub-menu').hasClass('active')){ $('#section-sub-menu').addClass('active').delay(300).addClass('shown'); $('#section-sub-menu-clear').addClass('active'); } if(!$('#section-sub-menu .rolling-img').hasClass('active')){ $('#section-sub-menu .rolling-img').delay(300).addClass('active'); }*/ $('#section-menu').addClass('active'); } else { $('#section-menu').removeClass('active'); /*if($('#section-sub-menu').hasClass('active')){ $('#section-sub-menu').removeClass('shown'); $('#section-sub-menu').removeClass('active'); $('#section-sub-menu-clear').removeClass('active'); } if($('#section-sub-menu .rolling-img').hasClass('active')){ $('#section-sub-menu .rolling-img').delay(300).removeClass('active'); }*/ } }); angular.element($window).bind('resize', function () { if ($(window).width() <= 991) { if ($('#section-sub-menu').hasClass('active')) { $('#section-sub-menu').removeClass('active'); $('#section-sub-menu-clear').removeClass('active'); } } else { $scope.mobileClose(); } }); }; return promise; }); _ui_share_app.directive('componentHeaderBar', function ($rootScope, $routeParams) { var templateName = 'componentHeaderBar'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath:'@imgpath', config_container:'@container', config_color:'@barcolor', config_scroll:'@onscroll', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'bar_first':'?barFirst', 'bar_second':'?barSecond', 'bar_third':'?barThird', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.use_container = (typeof $scope.config_container !== 'undefined' && $scope.config_container !== '') ? true : false; $scope.use_color = { first: { backgroundColor:'#ffffff', color:'#000000' }, second:{ backgroundColor:'#800000', color:'#ffffff' }, third: { backgroundColor:'#ffffff', color:'#000000' } }; $scope.on_scroll = {first: false, second:true, third:false}; $scope.assetsPath = 'extensions/themes/assets/'; $scope.$watch('config_color', function(newValue, oldValue){ if(!newValue || newValue == "") return; var stringArray = newValue.split("|"); if(typeof stringArray[0] !== 'undefined' && stringArray[0] !== ''){ /* First */ var a = stringArray[0].split(","); $scope.use_color.first.backgroundColor = a[0]; $scope.use_color.first.color = a[1]; } if(typeof stringArray[1] !== 'undefined' && stringArray[1] !== ''){ /* Second */ var b = stringArray[1].split(","); $scope.use_color.second.backgroundColor = b[0]; $scope.use_color.second.color = b[1]; } if(typeof stringArray[2] !== 'undefined' && stringArray[2] !== ''){ /* Third */ var c = stringArray[2].split(","); $scope.use_color.third.backgroundColor = c[0]; $scope.use_color.third.color = c[1]; } }); $scope.$watch('config_scroll', function(newValue, oldValue){ if(!newValue || newValue == "") return; var stringArray = newValue.split(","); if(typeof stringArray[0] !== 'undefined' && stringArray[0] !== ''){ $scope.on_scroll.first = stringArray[0]; } if(typeof stringArray[1] !== 'undefined' && stringArray[1] !== ''){ $scope.on_scroll.second = stringArray[1]; } if(typeof stringArray[2] !== 'undefined' && stringArray[2] !== ''){ $scope.on_scroll.third = stringArray[2]; } }); /* * mobile menu => close */ angular.element('[data-for="mobile_close"]').bind('click', function(){ angular.element('body').css('position','relative'); if(angular.element('.container_second_mobile .onActive').hasClass('active')){ angular.element('.container_second_mobile .onActive').removeClass('active'); } }); /* * mobile menu => open */ angular.element('[data-for="mobile_active"]').bind('click', function(){ angular.element('body').css('position','fixed'); if(!angular.element('.container_second_mobile .onActive').hasClass('active')){ angular.element('.container_second_mobile .onActive').addClass('active'); } }); /* * header mobile event on "scroll" */ angular.element($window).bind('scroll', function(){ if ($(document).scrollTop() > 240 && $(window).width() >= 931) { if(!angular.element('.container_second_scroll').hasClass('active')){ angular.element('.container_second_scroll').addClass('active'); } } else { if(angular.element('.container_second_scroll').hasClass('active')){ angular.element('.container_second_scroll').removeClass('active'); } } }); /* * header mobile event on "resize" */ angular.element($window).bind('resize', function(){ if($(document).width() >= 992){ angular.element('body').css('position','relative'); if(angular.element('.container_second_mobile .onActive').hasClass('active')){ angular.element('.container_second_mobile .onActive').removeClass('active'); } } }); $scope.goPath = function(t){ window.location.href=t; }; }; return promise; }); _ui_share_app.directive('componentHeaderCategory', function ($rootScope, $routeParams) { var templateName = 'componentHeaderCategory'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { primary:'@', secondary:'@', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data=[]; if($scope.data.length <= 0){ GAEAPI.get('referral/map',{'txt_referral_type_id':11}).then(function(e){ if(e.ok === 1) { $scope.data=e.data; } }); } }; return promise; }); _ui_share_app.directive('componentHeaderF', function ($rootScope, $routeParams) { var templateName = 'componentHeaderF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name :'@name', id:'=', background:'@', primary:'@', secondary:'@', imgpath:'@' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'menu_mobile':'?menuMobile', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.pixelCheck = 240; $scope.curTheme = CUR_THEME.shop_id(); /*if(CUR_THEME.shop_id()=="635"){ $scope.pixelCheck = 480; }*/ /* * header mobile event on "scroll" */ angular.element($window).bind('scroll', function(){ if(CUR_THEME.shop_id() != 741){ if ($(document).scrollTop() > $scope.pixelCheck && $(window).width() >= 931) { if(!angular.element('.desktop_scroll').hasClass('active')){ angular.element('.desktop_scroll').addClass('active'); } } else { if(angular.element('.desktop_scroll').hasClass('active')){ angular.element('.desktop_scroll').removeClass('active'); } } } }); /* * header mobile event on "resize" */ angular.element($window).bind('resize', function(){ if($(document).width() >= 992 && angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').removeClass('mobile_open_active'); $('body').css('overflow','auto'); } }); /* * active mobile menu */ $scope.activeMobileMenu=function(){ /* $('body').css('position','fixed'); */ if($( window ).width() < 991){ $('body').css('overflow','hidden'); } if(!angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').addClass('mobile_open_active'); } angular.element('._compoment_header .mobile').addClass('active'); }; /* * unactive mobile menu */ $scope.unactiveMobileMenu=function(){ /* $('body').css('position','relative'); */ $('body').css('overflow','auto'); if(angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').removeClass('mobile_open_active'); angular.element('.close').removeClass('active_x'); angular.element('.section').removeClass('active_y'); } }; $scope.goPath = function(t){ window.location.href=t; }; }; return promise; }); _ui_share_app.directive('componentHeaderG', function ($rootScope, $routeParams) { var templateName = 'componentHeaderG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name :'@name', id:'=', background:'@', primary:'@', secondary:'@', imgpath:'@' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'menu_mobile':'?menuMobile', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.pixelCheck = 240; $scope.curTheme = CUR_THEME.shop_id(); /*if(CUR_THEME.shop_id()=="635"){ $scope.pixelCheck = 480; }*/ /* * header mobile event on "scroll" */ angular.element($window).bind('scroll', function(){ if(CUR_THEME.shop_id() != 741){ if ($(document).scrollTop() > $scope.pixelCheck && $(window).width() >= 931) { if(!angular.element('.desktop_scroll').hasClass('active')){ angular.element('.desktop_scroll').addClass('active'); } } else { if(angular.element('.desktop_scroll').hasClass('active')){ angular.element('.desktop_scroll').removeClass('active'); } } } }); /* * header mobile event on "resize" */ angular.element($window).bind('resize', function(){ if($(document).width() >= 992 && angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').removeClass('mobile_open_active'); } }); /* * active mobile menu */ $scope.activeMobileMenu=function(){ /* $('body').css('position','fixed'); */ $('body').css('overflow','hidden'); if(!angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').addClass('mobile_open_active') } }; /* * unactive mobile menu */ $scope.unactiveMobileMenu=function(){ /* $('body').css('position','relative'); */ $('body').css('overflow','auto'); if(angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').removeClass('mobile_open_active'); angular.element('.close').removeClass('active_x'); angular.element('.section').removeClass('active_y'); } }; $scope.goPath = function(t){ window.location.href=t; }; }; return promise; }); _ui_share_app.directive('componentHeaderH', function ($rootScope, $routeParams) { var templateName = 'componentHeaderH'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name :'@name', id:'=', background:'@', primary:'@', secondary:'@', imgpath:'@' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'menu_mobile':'?menuMobile', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.pixelCheck = 240; $scope.curTheme = CUR_THEME.shop_id(); /*if(CUR_THEME.shop_id()=="635"){ $scope.pixelCheck = 480; }*/ /* * header mobile event on "scroll" */ angular.element($window).bind('scroll', function(){ if(CUR_THEME.shop_id() != 741){ if ($(document).scrollTop() > $scope.pixelCheck && $(window).width() >= 931) { if(!angular.element('.desktop_scroll').hasClass('active')){ angular.element('.desktop_scroll').addClass('active'); } } else { if(angular.element('.desktop_scroll').hasClass('active')){ angular.element('.desktop_scroll').removeClass('active'); } } } }); /* * header mobile event on "resize" */ angular.element($window).bind('resize', function(){ if($(document).width() >= 992 && angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').removeClass('mobile_open_active'); } }); /* * active mobile menu */ $scope.activeMobileMenu=function(){ /* $('body').css('position','fixed'); */ $('body').css('overflow','hidden'); if(!angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').addClass('mobile_open_active') } }; /* * unactive mobile menu */ $scope.unactiveMobileMenu=function(){ /* $('body').css('position','relative'); */ $('body').css('overflow','auto'); if(angular.element('._compoment_header').hasClass('mobile_open_active')){ angular.element('._compoment_header').removeClass('mobile_open_active'); angular.element('.close').removeClass('active_x'); angular.element('.section').removeClass('active_y'); } }; $scope.goPath = function(t){ window.location.href=t; }; }; return promise; }); _ui_share_app.directive('componentHeadline', function ($rootScope, $routeParams) { var templateName = 'componentHeadline'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._textSlide = []; $scope._gettextslide = function(){ $scope._textslide_data = []; GAEAPI.get('web/home',{} , $scope).then(function(res){ if(res.ok == 1){ $scope._textSlide = res.data.textslide_banner; } }); }; $scope._gettextslide(); }; return promise; }); _ui_share_app.directive('componentHello', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentHello'; var templatePathUrl = _ui_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', badgeid: '@badgeid', badgename: '@badgename', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) {}; promise.controller = function ($scope, $timeout, $interval, $q, $window, $location) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; }; return promise; }); _ui_share_app.factory('$componentHomePageVideo', function componentHomePageVideo($routeParams, $timeout) { return });_ui_share_app.directive('componentHomePageVideoTypeA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentHomePageVideoTypeA'; var componentMain = 'componentHomePageVideo'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { mobilesize: '@mobilesize', desktopsize: '@desktopsize', imageset : '@imageset', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = {}; GAEAPI.get('shop/current', dataSend).then(function(output) { if (output.ok === 1) { $scope._dataArray = output.data; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object, link) { $('#video-player').html(''); if (object !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.location.href = link; } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(''); $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); return; }; $scope.viewDataSize = function() { return ($(window).width() > 767) ? $scope.desktopsize : $scope.mobilesize; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.factory('$componentImage', function componentImage($routeParams, $timeout) { return });_ui_share_app.directive('componentImageGallerySlideA', function($rootScope, $routeParams) { var templateName = 'componentImageGallerySlideA'; var componentMain = 'componentImage'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', blogid: '@blogid', showbutton: '@showbutton', galleryid: '@galleryid', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarouselBlog = function(elem) { console.debug('mkCarouselBlog: trigger'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 4 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } } ] }).closest('section').addClass('active'); }, 1000); }; $scope._blogArray = []; $scope._blogArrayDone = false; $scope._getBlogArray = function() { $scope._blogArrayDone = false; $scope._blogArray = []; var filterJson = { 'image_group_id_array': [$scope.galleryid] }; var d = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(filterJson), }; GAEAPI.get('image/lists', d, $scope).then(function(e) { if (e.ok == 1) { $scope._blogArrayDone = true; $scope.data = e.data.dataList; console.log("image_group_id_array :", $scope.data); } }); }; $scope._getBlogArray(); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.setdispay = function(imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow', 'hidden'); } $scope.setdispayclose = function(imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow', 'visible'); } $scope.displayImage = function(image_url, prefix) {return GAEAPI.getGaeImageUrl(image_url, prefix);} }; return promise; });_ui_share_app.directive('componentImageGroupIdA', function($rootScope, $routeParams) { var templateName = 'componentImageGroupIdA'; var componentMain = 'componentImage'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { groupid: '@groupid', maxresult: '@maxresult', stylebutton: '@stylebutton', loadmore: '@loadmore', setloadmore: '@setloadmore', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data_per_page = $scope.maxresult; $scope.getsetloadmore = ($scope.setloadmore != undefined && $scope.setloadmore != "") ? $scope.setloadmore : false; $scope.getloadmore = ($scope.loadmore != undefined && $scope.loadmore != "") ? $scope.loadmore : 'Load More'; $scope.getbutton = ($scope.stylebutton != undefined && $scope.stylebutton != "") ? $scope.stylebutton : 'filled_button_small_round'; $scope.data_image = []; $scope.data_full = []; $scope.data_image_id = { load: true, done: false }; $scope.fetchTimes = 1; $scope.GETdata_image_id = function(cpage, ppage, id) { $scope.data_image = []; $scope.data_image_id.load = true; $scope.data_image_id.done = false; var d = { 'cur_page': cpage, 'per_page': ppage, 'txt_filter_json': JSON.stringify({ "image_group_id_array": [id] }) }; GAEAPI.get('image/lists', d, $scope).then(function(res) { if (res.ok == 1) { console.log("image/lists : ", res); $scope.data_image = res.data.dataList; $scope.data_full = res.data; } $scope.data_image_id.load = false; $scope.data_image_id.done = true; }); }; $scope.GETdata_image_id($scope.fetchTimes, $scope.data_per_page, $scope.groupid); $scope.loadMore = function() { $scope.data_per_page = parseInt($scope.data_per_page) + parseInt($scope.maxresult); $scope.GETdata_image_id($scope.fetchTimes, $scope.data_per_page, $scope.groupid); }; $scope.showDebug = function() { return (typeof $routeParams.debugimage !== 'undefined') ? true : false; }; $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; }; return promise; });_ui_share_app.directive('componentImageAa', function($rootScope, $routeParams, sliderProvider, carouselData, $location) { var templateName = 'componentImageAa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', type: '@type', margin: '@margin', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope._component = { name: "componentImageAa", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._margin = ($scope.margin != undefined && $scope.margin != "") ? { margin: $scope.margin } : { margin: 0 }; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getImageGroupId: function(params, callback) { var _self = this; var image_group_id = (params.image_group_id != undefined) ? params.image_group_id.split("-", 1).join("") : false; _self.consoleLog("getGalleryId ", "image_group_id", image_group_id); callback(image_group_id); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.control = function() { var getFunction = { popupImage: function(state, image) { var _self = this; console.log("popupImage image : ", image); $scope.data_control.image.popup = state; $scope.data_control.image.shop_image_url = ''; }, main: function() { var _self = this; } } return getFunction; }; /* get api */ $scope.data_control = { image: { popup: false, shop_image_url: "" } } $scope.data_api = { load_more: { load: false, cur_page: 1, per_page: 12, total_rows: 0 }, image: { data_send: {}, api: "image/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.loadMore = function() { if (!$scope.data_api.load_more.load) { $scope.data_api.load_more.cur_page++; $scope.data_api.load_more.load = true; $scope.getData().getRouteParams(function(_self, params, state) { _self.formatDataSend($scope.data_api.image, function(res_data) { _self.getImageGroupId(params, function(res_image_group_id) { var filter_json = { "image_group_id_array": [res_image_group_id] }; var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'image_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var oldData = res_data.data_array; res_data.data_array = oldData.concat(res_api.data.dataList); angular.forEach(res_data.data_array, function(item, index) { _self.getNameUrl(res_data.data_array[index].image_title, function(res_title) { res_data.data_array[index].image_title_url = res_title; }); }); $scope.data_api.load_more.total_rows = res_api.data.total_rows; } else { $scope.data_api.load_more.cur_page--; } $scope.data_api.load_more.load = false; }); }); }); }); }); } } $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.image.data_array_state = state; _self.formatDataSend($scope.data_api.image, function(res_data) { _self.getImageGroupId(params, function(res_image_group_id) { var filter_json = { "image_group_id_array": [res_image_group_id] }; var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'image_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getNameUrl(res_data.data_array[index].image_title, function(res_title) { res_data.data_array[index].image_title_url = res_title; }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; }); }); }); }); }); /* get api */ }; return promise; });_ui_share_app.directive('componentImageId', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentImageId'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { galleryid: '@galleryid', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data_photo_list = []; $scope.data = []; $scope.data_done = false; $scope.getData = function() { $scope.data = []; $scope.data_done = false; var filterJson = { 'image_group_id_array': [511] }; var d = { 'cur_page': 1, 'per_page': 8, 'txt_filter_json': JSON.stringify(filterJson), }; GAEAPI.get('image/lists', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data = e.data.dataList; console.log("image_group_id_array :", $scope.data); } }); }; $scope.getData(); $scope.setdispay = function(imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow', 'hidden'); } $scope.setdispayclose = function(imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow', 'visible'); } $scope.displayImage = function(image_url, prefix) {return GAEAPI.getGaeImageUrl(image_url, prefix);} }; return promise; });_ui_share_app.directive('componentImageIdSlide', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentImageIdSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { galleryid: '@galleryid', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data_photo_list = []; $scope.data = []; $scope.data_done = false; $scope.type = 'AlbumSlide'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.getData = function () { $scope.data_done = false; var filterJson = { 'image_group_id_array': [514] }; var d = { 'cur_page': 1, 'per_page': 12, 'txt_filter_json': JSON.stringify(filterJson), }; GAEAPI.get('image/lists', d, $scope).then(function (e) { if (e.ok == 1) { $scope.data = e.data.dataList; console.log("image_group_id_array :", $scope.data); } var resultArray = e.data.dataList; if (resultArray.length) { carouselData.set($scope.type, resultArray); console.log("datatest1232", resultArray); $scope.data = resultArray; } else { $scope.done = true; return; } var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); }); }; if (!carouselData.get($scope.type) && !$scope.data.length) { $scope.getData(); } else { $scope.data = carouselData.get($scope.type); console.log("%ccarouselData => get state", "background-color:yellow;color:black;padding:5px;"); var t = $interval(function () { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.initSlider(); }, 300); } }, 500); } $scope.displayImage = function (image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } $scope.imageSize = function () { return angular.element("img.image_lazy_loaded").length; }; $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.initSlider = function () { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: true, infinite: true, responsive: [ { breakpoint: 991, settings: { arrows: false, slidesToShow: 4 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } } ] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function () { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function (i) { var a = i; if (a.indexOf('http') == -1) { return 'http://' + i; } return i; }; $scope.slickGoLeft = function () { setTimeout(function () { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function () { setTimeout(function () { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.checkSeo = function () { return (GURL.isHtml5Mode()) ? true : false; }; /* Check if child array exist */ $scope.checkChild = function (object) { return (!object.referral_sub_array.length) ? true : false; }; $scope.buildTitleUrl = function (str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.data_gallery_name = []; $scope.galleryInit = function () { $scope.data_gallery_name = []; var d = { 'txt_image_group_id': $scope.galleryid, }; GAEAPI.get('image_group/id', d, $scope).then(function (e) { $scope.data_gallery_name = (e.ok == 1) ? e.data : []; }); }; $scope.galleryInit(); $scope.setdispay = function (imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow', 'hidden'); } $scope.setdispayclose = function (imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow', 'visible'); } }; return promise; }); _ui_share_app.directive('componentImageViewS', function ($rootScope, $routeParams, $location) { var templateName = 'componentImageViewS'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgurl: '@imgurl', imgpath: '@imgpath', imgid: '@imgid', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.setdispay = function (imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow','hidden'); } $scope.setdispayclose = function (imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow','visible'); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); $scope.checkSeo = function () { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function (str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.checkColorConfig = function () { return ($('config-color').length) ? true : false; }; }; return promise; }); _ui_share_app.directive('componentLightmax', function($rootScope, $routeParams, $location) { var templateName = 'componentLightmax'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = { name: "componentLightmax", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope._margin = ($scope.margin != undefined && $scope.margin != "") ? { margin: $scope.margin } : { margin: 0 }; $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, getHeader: function(params, callback) { var _self = this; _self.consoleLog("getHeader", "params", params); var custom_id = (params.custom_id != undefined) ? params.custom_id : "review"; var header_array = [{ name: ["review", "สินค้าและบริการ"] }, { name: ["main_recommend", "สินค้าแนะนำ"] }, { name: ["image_group_recommend", "อัลบั้มสินค้าแนะนำ"] }, { name: ["video_lists_recommend", "วีดีโอสินค้าแนะนำ"] }, { name: ["main_service", "การบริการ"] }, { name: ["image_group_lists", "อัลบั้มรูปภาพ"] }, { name: ["image_lists", "รูปภาพ"] }, { name: ["image_recommend", "รูปภาพสินค้าแนะนำ"] }]; var header = []; header.push(custom_id); header.push(custom_id); angular.forEach(header_array, function(item, index) { if (item.name[0] == custom_id) { header = item.name; } }); callback(header[0], header[1]); }, main: function() { var _self = this; } } return getFunction; }; $scope.control = function() { var getFunction = { popupImage: function(state, image) { var _self = this; $scope.data_control.image.popup = state; $scope.data_control.image.shop_image_url = ''; }, popupVideo: function(state, video_link, video_embed_code) { var _self = this; if (video_embed_code != '') { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } else if (video_link != '') { window.open(video_link, '_blank'); } else { $scope.data_control.page_video.popup = false; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } }, main: function() { var _self = this; } } return getFunction; }; $scope.data_control = { image: { popup: false, shop_image_url: "" }, page_video: { popup: false, shop_video_embed_code: "" } } $scope.data_api = { header: "", header_main: "", /** main custom recommend **/ main_recommend: [{ page_url: "custom/image_group_recommend", data_array: { gallery_image: [{ image_url: "https://image.getappeasy.com/src/images/2000/1431/0659/431659t1570014370.jpg", }] }, data_array_state: { load: false, done: true } }, { page_url: "custom/video_lists_recommend", data_array: { gallery_image: [{ image_url: "https://image.getappeasy.com/src/images/2000/1431/0330/431330t1569819231.jpg", }] }, data_array_state: { load: false, done: true } }], /** main custom recommend **/ /** image group recommend **/ image_group_recommend: [{ load_more: { load: false, cur_page: 1, per_page: 12, total_rows: 0 }, page_url: "custom/image_lists", data_send: {}, api: "image_group/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } }], /** image group recommend **/ /** video lists recommend **/ video_lists_recommend: [{ load_more: { load: false, cur_page: 1, per_page: 12, total_rows: 0 }, page_url: "", data_send: {}, api: "video/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } }], /** video lists recommend **/ /** main custom service **/ main_service: [{ load_more: { load: false, cur_page: 1, per_page: 12, total_rows: 0 }, page_url: "custom/image_group_lists", data_send: {}, api: "gallery/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } }], /** main custom service **/ /** image group lists **/ image_group_lists: [{ load_more: { load: false, cur_page: 1, per_page: 12, total_rows: 0 }, page_url: "custom/image_lists", data_send: {}, api: "image_group/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } }], /** image group lists **/ /** image lists in group **/ image_lists: [{ load_more: { load: false, cur_page: 1, per_page: 12, total_rows: 0 }, page_url: "", data_send: {}, api: "image/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } }], /** image lists in group **/ } $scope.getData().getRouteParams(function(_self, params, state) { _self.getHeader(params, function(header_main, res_header) { $scope.data_api.header = res_header; $scope.data_api.header_main = header_main; switch (header_main) { case "main_recommend": break; case "image_group_recommend": angular.forEach($scope.data_api.image_group_recommend, function(item, index) { item.data_array_state = state; _self.formatDataSend(item, function(res_data) { var filter_json = { 'gallery_id_array': [266] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'image_group_create_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; res_data.data_array_state = res_state; res_data.load_more.total_rows = res_api.data.total_rows; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); break; case "video_lists_recommend": angular.forEach($scope.data_api.video_lists_recommend, function(item, index) { item.data_array_state = state; _self.formatDataSend(item, function(res_data) { var filter_json = { 'badge_id_array': [18] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'video_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; res_data.data_array_state = res_state; res_data.load_more.total_rows = res_api.data.total_rows; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); break; case "main_service": angular.forEach($scope.data_api.main_service, function(item, index) { item.data_array_state = state; _self.formatDataSend(item, function(res_data) { var filter_json = { 'gallery_id_array': [191, 195] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'gallery_create_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; res_data.data_array_state = res_state; res_data.load_more.total_rows = res_api.data.total_rows; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); break; case "image_group_lists": var dataSend = { 'txt_gallery_id': params.gallery_id, }; _self.dataSend("gallery/id", dataSend, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { $scope.data_api.header = res_api.data.gallery_name; _self.consoleLog("getApiData", "res_api", res_api); }); }); angular.forEach($scope.data_api.image_group_lists, function(item, index) { item.data_array_state = state; _self.formatDataSend(item, function(res_data) { var filter_json = { 'gallery_id_array': [params.gallery_id] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'image_group_create_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; res_data.data_array_state = res_state; res_data.load_more.total_rows = res_api.data.total_rows; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); break; case "image_lists": var dataSend = { 'txt_image_group_id': params.image_group_id, }; _self.dataSend("image_group/id", dataSend, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { $scope.data_api.header = res_api.data.image_group_name; _self.consoleLog("getApiData", "res_api", res_api); }); }); angular.forEach($scope.data_api.image_lists, function(item, index) { item.data_array_state = state; _self.formatDataSend(item, function(res_data) { var filter_json = { 'image_group_id_array': [params.image_group_id] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'image_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; res_data.data_array_state = res_state; res_data.load_more.total_rows = res_api.data.total_rows; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); break; default: break; } }); }); $scope.loadMore = function() { $scope.getData().getRouteParams(function(_self, params, state) { _self.getHeader(params, function(header_main, res_header) { switch (header_main) { case "main_recommend": break; case "image_group_recommend": angular.forEach($scope.data_api.image_group_recommend, function(item, index) { if (!item.load_more.load) { item.load_more.load = true; item.load_more.cur_page++; _self.formatDataSend(item, function(res_data) { var filter_json = { 'gallery_id_array': [266] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'image_group_create_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var old_data = res_data.data_array; res_data.load_more.total_rows = res_api.data.total_rows; res_data.data_array = old_data.concat(res_api.data.dataList); } else { item.load_more.cur_page--; } item.load_more.load = false; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); } }); break; case "video_lists_recommend": angular.forEach($scope.data_api.video_lists_recommend, function(item, index) { if (!item.load_more.load) { item.load_more.load = true; item.load_more.cur_page++; _self.formatDataSend(item, function(res_data) { var filter_json = { 'badge_id_array': [18] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'video_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var old_data = res_data.data_array; res_data.load_more.total_rows = res_api.data.total_rows; res_data.data_array = old_data.concat(res_api.data.dataList); } else { item.load_more.cur_page--; } item.load_more.load = false; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); } }); break; case "main_service": angular.forEach($scope.data_api.main_service, function(item, index) { if (!item.load_more.load) { item.load_more.load = true; item.load_more.cur_page++; _self.formatDataSend(item, function(res_data) { var filter_json = { 'gallery_id_array': [191, 195] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'gallery_create_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var old_data = res_data.data_array; res_data.load_more.total_rows = res_api.data.total_rows; res_data.data_array = old_data.concat(res_api.data.dataList); } else { item.load_more.cur_page--; } item.load_more.load = false; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); } }); break; case "image_group_lists": angular.forEach($scope.data_api.image_group_lists, function(item, index) { if (!item.load_more.load) { item.load_more.load = true; item.load_more.cur_page++; _self.formatDataSend(item, function(res_data) { var filter_json = { 'gallery_id_array': [params.gallery_id] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'image_group_create_time_DESC', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var old_data = res_data.data_array; res_data.load_more.total_rows = res_api.data.total_rows; res_data.data_array = old_data.concat(res_api.data.dataList); } else { item.load_more.cur_page--; } item.load_more.load = false; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); } }); break; case "image_lists": angular.forEach($scope.data_api.image_lists, function(item, index) { if (!item.load_more.load) { item.load_more.load = true; item.load_more.cur_page++; _self.formatDataSend(item, function(res_data) { var filter_json = { 'image_group_id_array': [params.image_group_id] }; var dataSend = { 'cur_page': item.load_more.cur_page, 'per_page': item.load_more.per_page, 'txt_sortby': 'image_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var old_data = res_data.data_array; res_data.load_more.total_rows = res_api.data.total_rows; res_data.data_array = old_data.concat(res_api.data.dataList); } else { item.load_more.cur_page--; } item.load_more.load = false; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); } }); break; default: break; } }); }); }; }; return promise; });/* Cart displat at right side of page */ var $inloginPopup = {}; /* params */ $inloginPopup.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentLogin/"; $inloginPopup.templateRoot = 'root.php'; $inloginPopup.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inloginPopup.indexCout = 0; $inloginPopup.reload = false; $inloginPopup.reload_page_url = ""; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inloginPopup.install = function(shopId, customBuild, reload, reload_page) { $inloginPopup.reload = reload; $inloginPopup.reload_page_url = reload_page != ""?reload_page:false; /* dont install in (checkout, login) */ this.templateRoot = 'root.php'; $.get($inloginPopup.path + 'componentLogin.css', function(response) { $('head').append(''); }); $.get($inloginPopup.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inloginPopup.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; /* Install */ /* installFacebook */ $inloginPopup.windowFbAsyncInit = function(appId_in, status_in, xfbml_in, version_in) { $inloginPopup.displayView().consoleLog("windowFbAsyncInit : appId_in : ", appId_in); $inloginPopup.displayView().consoleLog("windowFbAsyncInit : status_in : ", status_in); $inloginPopup.displayView().consoleLog("windowFbAsyncInit : xfbml_in : ", xfbml_in); $inloginPopup.displayView().consoleLog("windowFbAsyncInit : version_in : ", version_in); window.fbAsyncInit = function() { FB.init({ appId: appId_in, status: status_in, /* cookie: cookie_in, */ xfbml: xfbml_in, version: version_in }); FB.getLoginStatus(function(response) { $inloginPopup.displayView().consoleLog("getLoginStatus : response.status : ", response.status); if (response.status === "connected") { /* alert("getLoginStatus : response.status : ", "connected"); */ var windowLocationHref = window.location.href; var check = "code="; if (windowLocationHref.indexOf(check) != -1) { $inloginPopup.checkLoginFacebook(response, function(statusChangeCallback) { $inloginPopup.displayView().consoleLog("windowFbAsyncInit : checkLoginFacebook : statusChangeCallback : ", statusChangeCallback); if (statusChangeCallback) { window.location = encodeURI(encodeURI($inloginPopup.shop_domain)); /* location.reload(); */ } }); } } else { var status_login = UiCustomerBox.delegate.get.isLogin(); $inloginPopup.displayView().consoleLog("windowFbAsyncInit : status_login : ", status_login); /* if (!status_login) { GAEAPI.get('customer/logout', {}).then(function(output_logout) { if (output_logout.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); } */ } }, true); /* FB.AppEvents.logPageView(); */ }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }; $inloginPopup.facebook_app_id = ''; $inloginPopup.shop_domain = ''; $inloginPopup.setInstallFacebook = function(facebook_app_id, shop_domain, callback) { $inloginPopup.displayView().consoleLog("setInstallFacebook : facebook_app_id : ", facebook_app_id); $inloginPopup.displayView().consoleLog("setInstallFacebook : shop_domain : ", shop_domain); var statu_install_facebook = false; if (facebook_app_id != "") { statu_install_facebook = true; $inloginPopup.windowFbAsyncInit(facebook_app_id, true, true, 'v3.1'); } callback(statu_install_facebook); }; /*---------------------------*/ $inloginPopup.checkLoginFacebook = function(response, callback) { $inloginPopup.statusChangeCallback(response, function(status_change_callback) { $inloginPopup.displayView().consoleLog("checkLoginFacebook : statusChangeCallback : status_change_callback : ", status_change_callback); callback(status_change_callback); }); }; $inloginPopup.statusChangeCallback = function(response, callback) { function waitForElement(){ try { $inloginPopup.displayView().consoleLog("status_change_callback : response : ", response); $inloginPopup.displayView().consoleLog("statusChangeCallback : response.status : ", response.status); var status_change_callback = false; /* response.status : connected */ if (response.status === "connected") { /* FB.login(function(response) {}, { scope: 'email' }); */ /* alert("response.status : ", response.status); */ FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) { $inloginPopup.displayView().consoleLog("statusChangeCallback : connected : FB.api : response : ", response); }); $inloginPopup.displayView().consoleLog("statusChangeCallback : connected : response : ", response); var dataSend = { txt_fb_access_token: response.authResponse.accessToken, }; $inloginPopup.displayView().consoleLog("statusChangeCallback : UiCustomerBox : ", (typeof UiCustomerBox != undefined)); $inloginPopup.displayView().consoleLog("statusChangeCallback : UiCustomerBox.api : ", (typeof UiCustomerBox.api != undefined)); $inloginPopup.displayView().consoleLog("statusChangeCallback : UiCustomerBox.api.post : ", UiCustomerBox.api.post); $inloginPopup.displayView().consoleLog("statusChangeCallback : connected : dataSend : ", dataSend); UiCustomerBox.api.post("customer/facebook_login", dataSend).then(function(output) { $inloginPopup.displayView().consoleLog("statusChangeCallback : connected : UiCustomerBox : output : ", output); if (output.ok == 1) { $inloginPopup.displayView().consoleLog("statusChangeCallback : connected : UiCustomerBox : output : ", "PASS"); UiCustomerBox.callEventScript("on.justLogin", output.data); setTimeout(function() { $inloginPopup.helper.pageUnLoad(); $inloginPopup.close(); $inregisterPopup.close(); }, 100); if (output.data.customer_email == "") { var dataSend = {}; GAEAPI.get('customer/logout', dataSend).then(function(output) { if (output.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); alert("ไม่สามารถใช้ Facebook ของท่านเข้าระบบได้ กรุณาผูกเมล์ใน Facebook ของท่านก่อน แล้วลองอีกครั้ง"); } UiCustomerBox.apiGetCustomerData(function() {}); } else { $inloginPopup.displayView().consoleLog("statusChangeCallback : connected : UiCustomerBox : output : ", "ERROR"); } status_change_callback = true; callback(status_change_callback); }); } /* response.status : not_authorized */ else if (response.status == "not_authorized") { window.location = encodeURI("https://www.facebook.com/v3.1/dialog/oauth?app_id=" + $inloginPopup.facebook_app_id + "&redirect_uri=" + encodeURI($inloginPopup.shop_domain) + "&scope=email"); callback(status_change_callback); } /* response.status : unknown */ else if (response.status == "unknown") { window.location = encodeURI("https://www.facebook.com/v3.1/dialog/oauth?app_id=" + $inloginPopup.facebook_app_id + "&redirect_uri=" + encodeURI($inloginPopup.shop_domain) + "&scope=email"); callback(status_change_callback); } } catch (err) { $inloginPopup.displayView().consoleLog("status_change_callback : response err : ", response); $inloginPopup.displayView().consoleLog("statusChangeCallback : response.status err : ", response.status); setTimeout(function() { waitForElement(); }, 4000); } } waitForElement(); }; $inloginPopup.loginFacebook = function() { $inloginPopup.displayView().consoleLog("loginFacebook : statu : ", "start"); FB.getLoginStatus(function(response) { $inloginPopup.displayView().consoleLog("loginFacebook : getLoginStatus : response : ", response); $inloginPopup.statusChangeCallback(response, function(status_change_callback) { $inloginPopup.displayView().consoleLog("loginFacebook : statusChangeCallback : status_change_callback : ", status_change_callback); if (!status_change_callback) { var locationHref = window.location.href; window.localStorage.setItem('loginFacebook', locationHref); } }); }, true); }; /*---------------------------*/ $inloginPopup.installFacebook = function(facebook_app_id, shop_domain) { $inloginPopup.displayView().consoleLog("installFacebook : facebook_app_id : ", facebook_app_id); $inloginPopup.displayView().consoleLog("installFacebook : shop_domain : ", shop_domain); $inloginPopup.setInstallFacebook(facebook_app_id, shop_domain, function(statu_install_facebook) { $inloginPopup.displayView().consoleLog("installFacebook : setInstallFacebook : statu_install_facebook : ", statu_install_facebook); if (statu_install_facebook) { $inloginPopup.facebook_app_id = facebook_app_id; $inloginPopup.shop_domain = shop_domain; $inloginPopup.login.facebook = true; setTimeout(function() { try { FB.getLoginStatus(function(response) { $inloginPopup.displayView().consoleLog("getLoginStatus : response.status : ", response.status); if (response.status === "connected") { var windowLocationHref = window.location.href; var check = "code="; if (windowLocationHref.indexOf(check) != -1) { $inloginPopup.checkLoginFacebook(response, function(statusChangeCallback) { $inloginPopup.displayView().consoleLog("installFacebook : checkLoginFacebook : statusChangeCallback : ", statusChangeCallback); if (statusChangeCallback) { var loginFacebookIs = window.localStorage.getItem('loginFacebook'); window.localStorage.removeItem('loginFacebook'); var callback_page = (loginFacebookIs != null && loginFacebookIs != undefined) ? loginFacebookIs : $inloginPopup.shop_domain; window.location = encodeURI(encodeURI(callback_page)); } }); } } }, true); } catch (err) { $inloginPopup.displayView().consoleLog("getLoginStatus : response.status : ", "error"); } }, 1500); } }); }; /* installFacebook */ /* displayView */ $inloginPopup.displayView = function() { var display = { consoleLog: function(statu, data) { var statuConsole = true; if (statuConsole) { console.log(statu, data); } }, }; return display; }; /* displayView */ /* login model */ $inloginPopup.getMe = {}; $inloginPopup.login = { email: '', password: '', remember: false, pressing: false, errore_mail: false, errore_password: false, facebook: false, twitter: false, google: false, }; $inloginPopup.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* login model */ /* validateLogin */ $inloginPopup.validateLogin = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inloginPopup.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inloginPopup.error.email = false; $inloginPopup.error.emailExist = false; $('#login-email-v1').css('border', ''); }, focusPassword: function() { $inloginPopup.error_password = false; $inloginPopup.error.wrong_password = false; $('#login-password-v1').css('border', ''); }, email: function() { var v = $('#login-email-v1').val(); var t = this; if (v.length <= 0) { $inloginPopup.shake(); $inloginPopup.validateLogin().emailInputNullError(); $inloginPopup.error_email = false; $inloginPopup.error_emailExist = false; return false; } else { var valid = $inloginPopup.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inloginPopup.shake(); $inloginPopup.validateLogin().emailInputError(); $inloginPopup.error_email = true; return false; } else if (v.length > 0 && valid) { $inloginPopup.validateLogin().emailOk(); return true; } } }, emailOk: function() { $('#login-email-v1').css('border', '2px solid green'); $inloginPopup.validateLogin().emailInputOk(); }, emailInputOk: function() { $("#login-error-email").removeClass("error"); $("#login-error-email").css('opacity', 0); }, emailError: function() { $("#login-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inloginPopup.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล Email should be valid'); }, emailInputNotFoundError: function() { $inloginPopup.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ไม่พบอีเมลนี้ในข้อมูลสมาชิก Email is not found'); }, emailInputNullError: function() { $inloginPopup.validateLogin().emailError(); $("#login-error-email").addClass("error"); // $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#login-password-v1').val(); if (v.length <= 0) { $inloginPopup.validateLogin().passwordInputNullError(); $inloginPopup.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inloginPopup.error_password = false; /*$inloginPopup.validateLogin().passwordOk();*/ return true; } else if (v.length > 0 && v.length < 6) { $inloginPopup.error_password = true; $inloginPopup.shake(); $inloginPopup.validateLogin().passwordInputError(); return false; } }, passwordOk: function() { $("#login-password-v1").css('border', '2px solid green'); $inloginPopup.validateLogin().passwordInputOk(); }, passwordInputOk: function() { $("#login-error-password").removeClass("error"); $("#login-error-password").css('opacity', 0); }, passwordError: function() { $("#login-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inloginPopup.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputPasswordWrongError: function() { $inloginPopup.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('รหัสไม่ถูกต้อง Password is wrong'); }, passwordInputNullError: function() { $inloginPopup.validateLogin().passwordError(); $("#login-error-password").addClass("error"); // $("#login-error-password").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetEmail: function() { $("#login-email-v1").css('border', ''); $("#login-email-v1").val(''); $("#login-error-email").css('opacity', 0); }, resetPassword: function() { $("#login-password-v1").css('border', ''); $("#login-password-v1").val(''); $("#login-error-password").css('opacity', 0); }, reset: function() { $inloginPopup.validateLogin().resetEmail(); $inloginPopup.validateLogin().resetPassword(); }, }; return promise; }; /* validateLogin */ /* load html */ $inloginPopup.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inloginPopup.whenOnLoad = function(shopId) {}; $inloginPopup.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.login_v1_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.login_v1_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitLogin */ $inloginPopup.submitLogin = function() { $inloginPopup.login.email = $('#login-email-v1').val(); $inloginPopup.login.password = $('#login-password-v1').val(); var userEmail = $inloginPopup.login.email; var userPass = $inloginPopup.login.password; var userEmailValid = $inloginPopup.validateLogin().email(); var userPassValid = $inloginPopup.validateLogin().password(); console.log("submitLogin", "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); if (!userEmailValid || !userPassValid) { console.log("submitLogin", "return"); $inloginPopup.shake(); return; } $inloginPopup.validateLogin().checkEmail(userEmail, function(resultCheck) { console.log("submitLogin", resultCheck); if (resultCheck.ok == 1) { console.log('submitLogin true'); $inloginPopup.validateLogin().emailInputNotFoundError(); $inloginPopup.validateLogin().passwordInputPasswordWrongError(); $inloginPopup.error.email = true; $inloginPopup.error.emailExist = true; } else { console.log('submitLogin false'); return $inloginPopup.sendSubmitLogin(false); } }); }; /* submitLogin */ /* sendSubmitLogin */ $inloginPopup.sendSubmitLogin = function(reCheck) { $inloginPopup.login.pressing = true; var userEmail = $inloginPopup.login.email; var userPass = $inloginPopup.login.password; // $inloginPopup.login.remember = $('#login-remember-v1')[0].checked; var userRemember = $inloginPopup.login.remember; console.log("sendSubmitLogin : userRemember", userRemember); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inloginPopup.validateLogin().emailInputError(); } else { $inloginPopup.validateLogin().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $inloginPopup.validateLogin().passwordOk(); } else { $inloginPopup.validateLogin().passwordInputError(); } /* email */ if (userEmail.length > 0 && !$inloginPopup.helper.isEmail(userEmail)) { $inloginPopup.error_email = true; } else { $inloginPopup.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inloginPopup.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inloginPopup.error_password = true; } if ($inloginPopup.error_password || $inloginPopup.error_email) { return; } } /* loading */ $inloginPopup.helper.pageLoad(); var token_login = {}; var hash_password = {}; var dataSendOne = { 'txt_email': userEmail }; var saveStorageData = {}; console.log("sendSubmitLogin : dataSendOne : ", dataSendOne); GAEAPI.post('customer/token_login', dataSendOne).then(function(e) { console.log("sendSubmitLogin : GAEAPI.post : e : ", e); token_login = e.data; var dataSendTwo = { 'txt_password': userPass, 'txt_key_token': token_login.key_token, 'txt_secret_token': token_login.secret_token, }; /* console.log("sendSubmitLogin : dataSendTwo", dataSendTwo); */ GAEAPI.post('customer/generate_hash_password', dataSendTwo).then(function(ee) { console.log("sendSubmitLogin : GAEAPI.post : ee : ", ee); hash_password = ee.data; var dataSendThree = { 'txt_email': userEmail, 'txt_hash_password': hash_password.hash_password }; /* console.log("sendSubmitLogin : dataSendThree : ", dataSendThree); */ saveStorageData.data_three = dataSendThree; GAEAPI.post('customer/login', dataSendThree).then(function(eee) { /* console.log("sendSubmitLogin : GAEAPI.post : eee : ", eee); */ /*console.log("login : done", eee);*/ if (eee.ok == 1) { var data = GAEAPI.getValue(eee.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(data, cookie_key, ""); saveStorageData.gae_access_token = gae_access_token; if (userRemember) { /*console.log("login : setting cookie");*/ GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 24 * 360)); setTimeout(function() { $inloginPopup.helper.pageUnLoad(); $inloginPopup.close(); }, 100); if ($inloginPopup.reload) { location.reload(); } } else { /* console.log("PressLogin -:- CookieLoginDestroy : "); */ console.log("PressLogin -:- CookieLoginDestroy : eee : ", eee); GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 3)); setTimeout(function() { $inloginPopup.helper.pageUnLoad(); $inloginPopup.close(); }, 100); $inloginPopup.getMe = eee.data; console.log("PressLogin -:- CookieLoginDestroy : getMe : ", $inloginPopup.getMe); UiCustomerBox.apiGetCustomerData(function() {}); if ($inloginPopup.reload) { location.reload(); } /* location.reload(); */ /* RELOAD URL() */ } } else { $inloginPopup.helper.pageUnLoad(); setTimeout(function() { $inloginPopup.validateLogin().passwordInputPasswordWrongError(); $inloginPopup.error.password = true; $inloginPopup.error.wrong_password = true; }, 500); } }); }); }); /* loading */ }; /* sendSubmitLogin */ /* viewPassword */ $inloginPopup.viewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); if (t === 'password') { e.setAttribute('type', 'text'); } else { e.setAttribute('type', 'password'); } return true; }; $inloginPopup.resetViewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); e.setAttribute('type', 'password'); return true; }; /* viewPassword */ $inloginPopup.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* loginSocialShow */ $inloginPopup.loginSocialShow = function() { /* $inloginPopup.login.facebook = face; $inloginPopup.login.twitter = twit; $inloginPopup.login.google = google; */ if (!$inloginPopup.login.facebook) { $('.heading.top_social').css('display', 'none'); $('.cover_from .login.from_background').css('height', 'auto'); $('.form_large .facebook').css('display', 'none'); } else {} if (!$inloginPopup.login.twitter) { $('.form_large .twitter').css('display', 'none'); } else {} if (!$inloginPopup.login.google) { $('.form_large .google').css('display', 'none'); } else {} } /* Open */ var timerAdjustOpen = 0; $inloginPopup.isOpen = false; $inloginPopup.open = function() { $inloginPopup.loginSocialShow(); $inloginPopup.resetViewPassword('login-password-v1'); $inloginPopup.validateLogin().reset(); $(".login_overlay").addClass("is_open"); $('body').css({ 'overflow': 'hidden', 'height': '100%' }); timerAdjustOpen = setTimeout(function() { $(".login.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inloginPopup.submitLogin(); } }); }; /* Open */ /* Close */ $inloginPopup.close = function() { $(".login_overlay").removeClass("is_open"); $(".login.from_background").removeClass("is_open"); $('body').css({ 'overflow': 'auto' }); }; /* Close */ /* shake */ $inloginPopup.shake = function() { $(".login.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".login.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* register */ $inloginPopup.register = function() { $inloginPopup.close(); $inregisterPopup.open(); } /* register */ /* register */ $inloginPopup.forgotpassword = function() { $inloginPopup.close(); $inforgotpasswordPopup.open() } /* register */ /* Init */ /* Init */ /* Init */ $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { /* normal design */ case 413: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://mtopup.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 448: $inloginPopup.install(currentShopId, false, false, "https://letsracethailand.com/product-list"); $inloginPopup.installFacebook("1750305688569018", "https://letsracethailand.com/product-list"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 467: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://maccordy.getappeasy.com"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break case 474: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://rmaphone.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 488: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("229573667786805", "https://deedee168.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 500: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("342067496316615", "https://missmonribs.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 536: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("874028079457760", "https://smart.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 541: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("2008736959365599", "https://zoomcamera.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; /* case 544: $inloginPopup.install(currentShopId, false, true); $inloginPopup.installFacebook("553027035120781", "https://sirikhun.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; */ case 598: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://krthai.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; /* case 635: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("172135180261900", "https://lightmax.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; */ case 646: $inloginPopup.install(currentShopId, false, true); $inloginPopup.installFacebook("201075893981111", "https://myhappyphones.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 647: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("193873407895720", "https://zaapclassic.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 676: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("946160295550680", "https://flashmalls.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 699: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("2154272628025686", "https://worldcamera.co.th/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 717: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("167421957160178", "https://hongminrestaurant.net/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 718: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("347439082330777", "https://seselect.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 723: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("202569956996401", "https://eindhoven.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 726: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("139758080204262", "https://pet2home.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 728: $inloginPopup.install(currentShopId, false, true, ""); $inloginPopup.installFacebook("194860237791443", "https://savehouse.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 729: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("202569956996401", "https://movementplayground.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 732: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("180024385979681", "https://tastyshabu.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 738: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("257158781691422", "https://misamisa.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 731: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("629913650678595", "https://iambeauty.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 737: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("1701672553201950", "https://gosowell.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 740: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://memento.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 741: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("816760211846604", "https://dacsee.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; /* case 742: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("1267373963396891", "https://funfong.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; */ case 743: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("400916763710626", "https://smarthome.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 747: $inloginPopup.install(currentShopId, false, true, ""); $inloginPopup.installFacebook("284335175689274", "https://uandv.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 750: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://npd.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 636: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("963882733822420", "https://allbestk.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 753: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://infosat.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 758: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("438859629951346", "https://khongfakthailand2018.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 785: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://proplay.getappeasy.com"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 713: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://gygy.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 535: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://honda.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 765: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://supercheap.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 523: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://magic.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 528: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://gaoyang.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 498: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://apbeauty.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 701: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://khumkhao.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 767: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://mammaherbal.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 770: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://zeus.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 771: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://etim.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 772: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://21style.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 773: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://klangchohuay.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 774: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://ddmusicroom.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 776: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://tsr.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 777: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://bypshop.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 459: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://xspeed.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 783: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("1199113323593330", "https://khunmaejuphuket.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 786: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://geniusgadgets.getappeasy.com"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 787: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "http://gdemo001.getappeasy.com"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 788: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "http://gdemo000.getappeasy.com"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 795: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "http://sirin.getappeasy.com"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 797: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "http://sirin.getappeasy.com"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 799: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://floristmaker.getappeasy.com"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 800: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("530537614372186", "https://finndelivery.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; case 801: $inloginPopup.install(currentShopId, false, false, ""); $inloginPopup.installFacebook("", "https://slumberland.getappeasy.com/"); $inregisterPopup.install(currentShopId, false); $inforgotpasswordPopup.install(currentShopId, false); break; default: break; } }); /* https://blog.logrocket.com/the-complete-guide-to-using-localstorage-in-javascript-apps-ba44edb53a36/ *//* Cart displat at right side of page */ var $inloginPopupTypeCct = {}; /* params */ $inloginPopupTypeCct.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentLoginTypeCct/"; $inloginPopupTypeCct.templateRoot = 'root.php'; $inloginPopupTypeCct.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inloginPopupTypeCct.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inloginPopupTypeCct.install = function(shopId, customBuild) { /* dont install in (checkout, login) */ this.templateRoot = 'root.php'; $.get($inloginPopupTypeCct.path + 'componentLoginTypeCct.css', function(response) { $('head').append(''); }); $.get($inloginPopupTypeCct.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inloginPopupTypeCct.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inloginPopupTypeCct.installFacebook = function(appID, Domain) { var facebook_js = "https://connect.facebook.net/en_US/sdk.js"; var facebookAppId = appID; /*console.log("installFacebook ", " Domain : ", Domain, " AppID : ", facebookAppId);*/ if (facebookAppId != "" && facebookAppId != undefined && facebookAppId != '000000000000000') { $inloginPopupTypeCct.login.facebook = true; window.fbAsyncInit = function() { FB.init({ appId: facebookAppId, cookie: true, xfbml: true, version: 'v2.8' }); FB.AppEvents.logPageView(); }; /* Load the SDK asynchronously */ (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = facebook_js; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); } else { $inloginPopupTypeCct.login.facebook = false; } }; $inloginPopupTypeCct.api = GURL.base_api_url(); /* Install */ /* login model */ $inloginPopupTypeCct.getMe = {}; $inloginPopupTypeCct.login = { email: '', password: '', remember: false, pressing: false, errore_mail: false, errore_password: false, facebook: false, twitter: false, google: false, }; $inloginPopupTypeCct.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* login model */ /* validateLogin */ $inloginPopupTypeCct.validateLogin = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inloginPopupTypeCct.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inloginPopupTypeCct.error.email = false; $inloginPopupTypeCct.error.emailExist = false; $('#login-email-v1').css('border', ''); }, focusPassword: function() { $inloginPopupTypeCct.error_password = false; $inloginPopupTypeCct.error.wrong_password = false; $('#login-password-v1').css('border', ''); }, email: function() { var v = $('#login-email-v1').val(); var t = this; if (v.length <= 0) { $inloginPopupTypeCct.shake(); $inloginPopupTypeCct.validateLogin().emailInputNullError(); $inloginPopupTypeCct.error_email = false; $inloginPopupTypeCct.error_emailExist = false; return false; } else { var valid = $inloginPopupTypeCct.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inloginPopupTypeCct.shake(); $inloginPopupTypeCct.validateLogin().emailInputError(); $inloginPopupTypeCct.error_email = true; return false; } else if (v.length > 0 && valid) { $inloginPopupTypeCct.validateLogin().emailOk(); return true; } } }, emailOk: function() { $('#login-email-v1').css('border', '2px solid green'); $inloginPopupTypeCct.validateLogin().emailInputOk(); }, emailInputOk: function() { $("#login-error-email").removeClass("error"); $("#login-error-email").css('opacity', 0); }, emailError: function() { $("#login-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inloginPopupTypeCct.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNotFoundError: function() { $inloginPopupTypeCct.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ไม่พบอีเมลนี้ในข้อมูลสมาชิก Email is not found'); }, emailInputNullError: function() { $inloginPopupTypeCct.validateLogin().emailError(); $("#login-error-email").addClass("error"); // $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#login-password-v1').val(); if (v.length <= 0) { $inloginPopupTypeCct.validateLogin().passwordInputNullError(); $inloginPopupTypeCct.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inloginPopupTypeCct.error_password = false; /*$inloginPopupTypeCct.validateLogin().passwordOk();*/ return true; } else if (v.length > 0 && v.length < 6) { $inloginPopupTypeCct.error_password = true; $inloginPopupTypeCct.shake(); $inloginPopupTypeCct.validateLogin().passwordInputError(); return false; } }, passwordOk: function() { $("#login-password-v1").css('border', '2px solid green'); $inloginPopupTypeCct.validateLogin().passwordInputOk(); }, passwordInputOk: function() { $("#login-error-password").removeClass("error"); $("#login-error-password").css('opacity', 0); }, passwordError: function() { $("#login-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inloginPopupTypeCct.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputPasswordWrongError: function() { $inloginPopupTypeCct.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('รหัสไม่ถูกต้อง Password is wrong'); }, passwordInputNullError: function() { $inloginPopupTypeCct.validateLogin().passwordError(); $("#login-error-password").addClass("error"); // $("#login-error-password").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetEmail: function() { $("#login-email-v1").css('border', ''); $("#login-email-v1").val(''); $("#login-error-email").css('opacity', 0); }, resetPassword: function() { $("#login-password-v1").css('border', ''); $("#login-password-v1").val(''); $("#login-error-password").css('opacity', 0); }, reset: function() { $inloginPopupTypeCct.validateLogin().resetEmail(); $inloginPopupTypeCct.validateLogin().resetPassword(); }, }; return promise; }; /* validateLogin */ /* load html */ $inloginPopupTypeCct.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inloginPopupTypeCct.whenOnLoad = function(shopId) {}; $inloginPopupTypeCct.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.login_vCct_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.login_vCct_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitLogin */ $inloginPopupTypeCct.submitLogin = function() { $inloginPopupTypeCct.login.email = $('#login-email-v1').val(); $inloginPopupTypeCct.login.password = $('#login-password-v1').val(); var userEmail = $inloginPopupTypeCct.login.email; var userPass = $inloginPopupTypeCct.login.password; var userEmailValid = $inloginPopupTypeCct.validateLogin().email(); var userPassValid = $inloginPopupTypeCct.validateLogin().password(); /* console.log("submitLogin", "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); */ if (!userEmailValid || !userPassValid) { /* console.log("submitLogin", "return"); */ $inloginPopupTypeCct.shake(); return; } $inloginPopupTypeCct.validateLogin().checkEmail(userEmail, function(resultCheck) { /* console.log("submitLogin", resultCheck); */ if (resultCheck.ok == 1) { /* console.log('submitLogin true'); */ $inloginPopupTypeCct.validateLogin().emailInputNotFoundError(); $inloginPopupTypeCct.validateLogin().passwordInputPasswordWrongError(); $inloginPopupTypeCct.error.email = true; $inloginPopupTypeCct.error.emailExist = true; } else { /* console.log('submitLogin false'); */ return $inloginPopupTypeCct.sendSubmitLogin(false); } }); }; /* submitLogin */ /* sendSubmitLogin */ $inloginPopupTypeCct.sendSubmitLogin = function(reCheck) { $inloginPopupTypeCct.login.pressing = true; var userEmail = $inloginPopupTypeCct.login.email; var userPass = $inloginPopupTypeCct.login.password; $inloginPopupTypeCct.login.remember = $('#login-remember-v1')[0].checked; var userRemember = $inloginPopupTypeCct.login.remember; /*console.log("userRemember", userRemember);*/ if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inloginPopupTypeCct.validateLogin().emailInputError(); } else { $inloginPopupTypeCct.validateLogin().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $inloginPopupTypeCct.validateLogin().passwordOk(); } else { $inloginPopupTypeCct.validateLogin().passwordInputError(); } /* email */ if (userEmail.length > 0 && !$inloginPopupTypeCct.helper.isEmail(userEmail)) { $inloginPopupTypeCct.error_email = true; } else { $inloginPopupTypeCct.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inloginPopupTypeCct.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inloginPopupTypeCct.error_password = true; } if ($inloginPopupTypeCct.error_password || $inloginPopupTypeCct.error_email) { return; } } /* loading */ $inloginPopupTypeCct.helper.pageLoad(); var token_login = {}; var hash_password = {}; var dataSendOne = { 'txt_email': userEmail }; var saveStorageData = {}; GAEAPI.post('customer/token_login', dataSendOne).then(function(e) { token_login = e.data; var dataSendTwo = { 'txt_password': userPass, 'txt_key_token': token_login.key_token, 'txt_secret_token': token_login.secret_token, }; GAEAPI.post('customer/generate_hash_password', dataSendTwo).then(function(ee) { hash_password = ee.data; var dataSendThree = { 'txt_email': userEmail, 'txt_hash_password': hash_password.hash_password }; saveStorageData.data_three = dataSendThree; GAEAPI.post('customer/login', dataSendThree).then(function(eee) { /* console.log("customer/login : done : ", eee); */ if (eee.ok == 1) { var data = GAEAPI.getValue(eee.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(data, cookie_key, ""); saveStorageData.gae_access_token = gae_access_token; if (userRemember) { /*console.log("login : setting cookie");*/ GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 24 * 360)); setTimeout(function() { $inloginPopupTypeCct.helper.pageUnLoad(); $inloginPopupTypeCct.close(); }, 100); } else { /* console.log("PressLogin -:- CookieLoginDestroy : "); */ console.log("PressLogin -:- CookieLoginDestroy : eee : ", eee); GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 3)); setTimeout(function() { $inloginPopupTypeCct.helper.pageUnLoad(); $inloginPopupTypeCct.close(); }, 100); $inloginPopupTypeCct.getMe = eee.data; console.log("PressLogin -:- CookieLoginDestroy : getMe : ", $inloginPopupTypeCct.getMe); UiCustomerBox.apiGetCustomerData(function() {}); /* location.reload(); */ /* RELOAD URL() */ } } else { $inloginPopupTypeCct.helper.pageUnLoad(); setTimeout(function() { $inloginPopupTypeCct.validateLogin().passwordInputError(); $inloginPopupTypeCct.error.password = true; $inloginPopupTypeCct.error.wrong_password = true; }, 500); } }); }); }); /* loading */ }; /* sendSubmitLogin */ /* viewPassword */ $inloginPopupTypeCct.viewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); if (t === 'password') { e.setAttribute('type', 'text'); } else { e.setAttribute('type', 'password'); } return true; }; $inloginPopupTypeCct.resetViewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); e.setAttribute('type', 'password'); return true; }; /* viewPassword */ $inloginPopupTypeCct.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* loginSocialShow */ $inloginPopupTypeCct.loginSocialShow = function() { /* $inloginPopupTypeCct.login.facebook = face; $inloginPopupTypeCct.login.twitter = twit; $inloginPopupTypeCct.login.google = google; */ if (!$inloginPopupTypeCct.login.facebook) { $('.form_large .facebook').css('display', 'none'); } else {} if (!$inloginPopupTypeCct.login.twitter) { $('.form_large .twitter').css('display', 'none'); } else {} if (!$inloginPopupTypeCct.login.google) { $('.form_large .google').css('display', 'none'); } else {} } /* Open */ var timerAdjustOpen = 0; $inloginPopupTypeCct.isOpen = false; $inloginPopupTypeCct.open = function() { $inloginPopupTypeCct.loginSocialShow(); $inloginPopupTypeCct.resetViewPassword('login-password-v1'); $inloginPopupTypeCct.validateLogin().reset(); $(".login_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'relative' }); timerAdjustOpen = setTimeout(function() { $(".login.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inloginPopupTypeCct.submitLogin(); } }); }; /* Open */ /* Close */ $inloginPopupTypeCct.close = function() { $(".login_overlay").removeClass("is_open"); $(".login.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inloginPopupTypeCct.shake = function() { $(".login.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".login.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* register */ $inloginPopupTypeCct.register = function() { $inloginPopupTypeCct.close(); $inverificationPopupTypeCct.open(); } /* register */ /* register */ $inloginPopupTypeCct.forgotpassword = function() { $inloginPopupTypeCct.close(); $inforgotpasswordPopupTypeCct.open() } /* register */ /* LoginFacebook */ $inloginPopupTypeCct.loginFacebook = function() { /*console.log("loginFacebook : loginFacebook ");*/ FB.getLoginStatus(function(response) { $inloginPopupTypeCct.statusChangeCallback(response); }); } $inloginPopupTypeCct.statusChangeCallback = function(response) { /*console.log("statusChangeCallback : ", response);*/ if (response.status === 'connected') { /*console.log("statusChangeCallback : if ", response);*/ } else { /*console.log("statusChangeCallback : else ", response);*/ } FB.login(function(response) { if (response.authResponse) { console.log("statusChangeCallback response.authResponse : ", response.authResponse); FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) { /*console.log('statusChangeCallback JSON : , ', JSON.stringify(response));*/ }); var accessToken = response.authResponse.accessToken; var user_id = response.authResponse.userID; var dataSend = { txt_fb_access_token: accessToken, }; /*console.log("statusChangeCallback : dataSend : ", dataSend);*/ UiCustomerBox.api.post("customer/facebook_login", dataSend).then(function(res) { /*console.log("customer/facebook_login : res", res);*/ if (res.ok == 1) { UiCustomerBox.callEventScript("on.justLogin", res.data); setTimeout(function() { $inloginPopupTypeCct.helper.pageUnLoad(); $inloginPopupTypeCct.close(); }, 100); UiCustomerBox.apiGetCustomerData(function() {}); /*location.reload();*/ /* RELOAD URL() */ } else { error.log('statusChangeCallback error.'); } }); } else { /*console.log('User cancelled login or did not fully authorize.');*/ } }, { scope: "email" }) } /* LoginFacebook */ /* Init */ /* Init */ /* Init */ $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { /* normal design */ case 429: $inloginPopupTypeCct.install(currentShopId, false); $inloginPopupTypeCct.installFacebook("000000000000000", "https://crowncentersuccess.getappeasy.com/"); $inverificationPopupTypeCct.install(currentShopId, false); $inregisterPopupTypeCct.install(currentShopId, false); $inforgotpasswordPopupTypeCct.install(currentShopId, false); break; default: break; } });/* Cart displat at right side of page */ var $inloginPopupTypeElc = {}; /* params */ $inloginPopupTypeElc.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentLoginTypeElc/"; $inloginPopupTypeElc.templateRoot = 'root.php'; $inloginPopupTypeElc.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inloginPopupTypeElc.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inloginPopupTypeElc.install = function(shopId, customBuild) { /* dont install in (checkout, login) */ this.templateRoot = 'root.php'; $.get($inloginPopupTypeElc.path + 'componentLoginTypeElc.css', function(response) { $('head').append(''); }); $.get($inloginPopupTypeElc.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inloginPopupTypeElc.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inloginPopupTypeElc.installFacebook = function(appID, Domain) { var facebook_js = "https://connect.facebook.net/en_US/sdk.js"; var facebookAppId = appID; /*console.log("installFacebook ", " Domain : ", Domain, " AppID : ", facebookAppId);*/ if (facebookAppId != "" && facebookAppId != undefined && facebookAppId != '000000000000000') { $inloginPopupTypeElc.login.facebook = true; window.fbAsyncInit = function() { FB.init({ appId: facebookAppId, cookie: true, xfbml: true, version: 'v2.8' }); FB.AppEvents.logPageView(); }; /* Load the SDK asynchronously */ (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = facebook_js; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); } else { $inloginPopupTypeElc.login.facebook = false; } }; $inloginPopupTypeElc.api = GURL.base_api_url(); /* Install */ /* login model */ $inloginPopupTypeElc.getMe = {}; $inloginPopupTypeElc.login = { email: '', password: '', remember: false, pressing: false, errore_mail: false, errore_password: false, facebook: false, twitter: false, google: false, }; $inloginPopupTypeElc.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* login model */ /* validateLogin */ $inloginPopupTypeElc.validateLogin = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inloginPopupTypeElc.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inloginPopupTypeElc.error.email = false; $inloginPopupTypeElc.error.emailExist = false; $('#login-email-v1').css('border', ''); }, focusPassword: function() { $inloginPopupTypeElc.error_password = false; $inloginPopupTypeElc.error.wrong_password = false; $('#login-password-v1').css('border', ''); }, email: function() { var v = $('#login-email-v1').val(); var t = this; if (v.length <= 0) { $inloginPopupTypeElc.shake(); $inloginPopupTypeElc.validateLogin().emailInputNullError(); $inloginPopupTypeElc.error_email = false; $inloginPopupTypeElc.error_emailExist = false; return false; } else { var valid = $inloginPopupTypeElc.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inloginPopupTypeElc.shake(); $inloginPopupTypeElc.validateLogin().emailInputError(); $inloginPopupTypeElc.error_email = true; return false; } else if (v.length > 0 && valid) { $inloginPopupTypeElc.validateLogin().emailOk(); return true; } } }, emailOk: function() { $('#login-email-v1').css('border', '2px solid green'); $inloginPopupTypeElc.validateLogin().emailInputOk(); }, emailInputOk: function() { $("#login-error-email").removeClass("error"); $("#login-error-email").css('opacity', 0); }, emailError: function() { $("#login-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inloginPopupTypeElc.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNotFoundError: function() { $inloginPopupTypeElc.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ไม่พบอีเมลนี้ในข้อมูลสมาชิก Email is not found'); }, emailInputNullError: function() { $inloginPopupTypeElc.validateLogin().emailError(); $("#login-error-email").addClass("error"); // $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#login-password-v1').val(); if (v.length <= 0) { $inloginPopupTypeElc.validateLogin().passwordInputNullError(); $inloginPopupTypeElc.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inloginPopupTypeElc.error_password = false; /*$inloginPopupTypeElc.validateLogin().passwordOk();*/ return true; } else if (v.length > 0 && v.length < 6) { $inloginPopupTypeElc.error_password = true; $inloginPopupTypeElc.shake(); $inloginPopupTypeElc.validateLogin().passwordInputError(); return false; } }, passwordOk: function() { $("#login-password-v1").css('border', '2px solid green'); $inloginPopupTypeElc.validateLogin().passwordInputOk(); }, passwordInputOk: function() { $("#login-error-password").removeClass("error"); $("#login-error-password").css('opacity', 0); }, passwordError: function() { $("#login-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inloginPopupTypeElc.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputPasswordWrongError: function() { $inloginPopupTypeElc.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('รหัสไม่ถูกต้อง Password is wrong'); }, passwordInputNullError: function() { $inloginPopupTypeElc.validateLogin().passwordError(); $("#login-error-password").addClass("error"); // $("#login-error-password").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetEmail: function() { $("#login-email-v1").css('border', ''); $("#login-email-v1").val(''); $("#login-error-email").css('opacity', 0); }, resetPassword: function() { $("#login-password-v1").css('border', ''); $("#login-password-v1").val(''); $("#login-error-password").css('opacity', 0); }, reset: function() { $inloginPopupTypeElc.validateLogin().resetEmail(); $inloginPopupTypeElc.validateLogin().resetPassword(); }, }; return promise; }; /* validateLogin */ /* load html */ $inloginPopupTypeElc.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inloginPopupTypeElc.whenOnLoad = function(shopId) {}; $inloginPopupTypeElc.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.login_vElc_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.login_vElc_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitLogin */ $inloginPopupTypeElc.submitLogin = function() { $inloginPopupTypeElc.login.email = $('#login-email-v1').val(); $inloginPopupTypeElc.login.password = $('#login-password-v1').val(); var userEmail = $inloginPopupTypeElc.login.email; var userPass = $inloginPopupTypeElc.login.password; var userEmailValid = $inloginPopupTypeElc.validateLogin().email(); var userPassValid = $inloginPopupTypeElc.validateLogin().password(); console.log("submitLogin", "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); if (!userEmailValid || !userPassValid) { console.log("submitLogin", "return"); $inloginPopupTypeElc.shake(); return; } $inloginPopupTypeElc.validateLogin().checkEmail(userEmail, function(resultCheck) { console.log("submitLogin", resultCheck); if (resultCheck.ok == 1) { console.log('submitLogin true'); $inloginPopupTypeElc.validateLogin().emailInputNotFoundError(); $inloginPopupTypeElc.validateLogin().passwordInputPasswordWrongError(); $inloginPopupTypeElc.error.email = true; $inloginPopupTypeElc.error.emailExist = true; } else { console.log('submitLogin false'); return $inloginPopupTypeElc.sendSubmitLogin(false); } }); }; /* submitLogin */ /* sendSubmitLogin */ $inloginPopupTypeElc.sendSubmitLogin = function(reCheck) { $inloginPopupTypeElc.login.pressing = true; var userEmail = $inloginPopupTypeElc.login.email; var userPass = $inloginPopupTypeElc.login.password; $inloginPopupTypeElc.login.remember = $('#login-remember-v1')[0].checked; var userRemember = $inloginPopupTypeElc.login.remember; console.log("sendSubmitLogin : userRemember : ", userRemember); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inloginPopupTypeElc.validateLogin().emailInputError(); } else { $inloginPopupTypeElc.validateLogin().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $inloginPopupTypeElc.validateLogin().passwordOk(); } else { $inloginPopupTypeElc.validateLogin().passwordInputError(); } /* email */ if (userEmail.length > 0 && !$inloginPopupTypeElc.helper.isEmail(userEmail)) { $inloginPopupTypeElc.error_email = true; } else { $inloginPopupTypeElc.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inloginPopupTypeElc.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inloginPopupTypeElc.error_password = true; } if ($inloginPopupTypeElc.error_password || $inloginPopupTypeElc.error_email) { return; } } /* loading */ $inloginPopupTypeElc.helper.pageLoad(); var token_login = {}; var hash_password = {}; var dataSendOne = { 'txt_email': userEmail }; var saveStorageData = {}; console.log("sendSubmitLogin : dataSendOne : ", dataSendOne); GAEAPI.post('customer/token_login', dataSendOne).then(function(e) { console.log("sendSubmitLogin : e : ", e); token_login = e.data; var dataSendTwo = { 'txt_password': userPass, 'txt_key_token': token_login.key_token, 'txt_secret_token': token_login.secret_token, }; GAEAPI.post('customer/generate_hash_password', dataSendTwo).then(function(ee) { hash_password = ee.data; var dataSendThree = { 'txt_email': userEmail, 'txt_hash_password': hash_password.hash_password }; saveStorageData.data_three = dataSendThree; GAEAPI.post('customer/login', dataSendThree).then(function(eee) { /* console.log("customer/login : done : ", eee); */ if (eee.ok == 1) { var data = GAEAPI.getValue(eee.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(data, cookie_key, ""); saveStorageData.gae_access_token = gae_access_token; if (userRemember) { /*console.log("login : setting cookie");*/ GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 24 * 360)); setTimeout(function() { $inloginPopupTypeElc.helper.pageUnLoad(); $inloginPopupTypeElc.close(); }, 100); } else { /* console.log("PressLogin -:- CookieLoginDestroy : "); */ console.log("PressLogin -:- CookieLoginDestroy : eee : ", eee); GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 3)); setTimeout(function() { $inloginPopupTypeElc.helper.pageUnLoad(); $inloginPopupTypeElc.close(); }, 100); $inloginPopupTypeElc.getMe = eee.data; console.log("PressLogin -:- CookieLoginDestroy : getMe : ", $inloginPopupTypeElc.getMe); UiCustomerBox.apiGetCustomerData(function() {}); /* location.reload(); */ /* RELOAD URL() */ } } else { $inloginPopupTypeElc.helper.pageUnLoad(); setTimeout(function() { $inloginPopupTypeElc.validateLogin().passwordInputError(); $inloginPopupTypeElc.error.password = true; $inloginPopupTypeElc.error.wrong_password = true; }, 500); } }); }); }); /* loading */ }; /* sendSubmitLogin */ /* viewPassword */ $inloginPopupTypeElc.viewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); if (t === 'password') { e.setAttribute('type', 'text'); } else { e.setAttribute('type', 'password'); } return true; }; $inloginPopupTypeElc.resetViewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); e.setAttribute('type', 'password'); return true; }; /* viewPassword */ $inloginPopupTypeElc.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* loginSocialShow */ $inloginPopupTypeElc.loginSocialShow = function() { /* $inloginPopupTypeElc.login.facebook = face; $inloginPopupTypeElc.login.twitter = twit; $inloginPopupTypeElc.login.google = google; */ if (!$inloginPopupTypeElc.login.facebook) { $('.form_large .facebook').css('display', 'none'); } else {} if (!$inloginPopupTypeElc.login.twitter) { $('.form_large .twitter').css('display', 'none'); } else {} if (!$inloginPopupTypeElc.login.google) { $('.form_large .google').css('display', 'none'); } else {} } /* Open */ var timerAdjustOpen = 0; $inloginPopupTypeElc.isOpen = false; $inloginPopupTypeElc.open = function() { $inloginPopupTypeElc.loginSocialShow(); $inloginPopupTypeElc.resetViewPassword('login-password-v1'); $inloginPopupTypeElc.validateLogin().reset(); $(".login_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'relative' }); timerAdjustOpen = setTimeout(function() { $(".login.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inloginPopupTypeElc.submitLogin(); } }); }; /* Open */ /* Close */ $inloginPopupTypeElc.close = function() { $(".login_overlay").removeClass("is_open"); $(".login.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inloginPopupTypeElc.shake = function() { $(".login.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".login.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* register */ $inloginPopupTypeElc.register = function() { $inloginPopupTypeElc.close(); $inregisterPopupTypeElc.open(); } /* register */ /* register */ $inloginPopupTypeElc.forgotpassword = function() { $inloginPopupTypeElc.close(); $inforgotpasswordPopupTypeElc.open() } /* register */ /* LoginFacebook */ $inloginPopupTypeElc.loginFacebook = function() { /*console.log("loginFacebook : loginFacebook ");*/ FB.getLoginStatus(function(response) { $inloginPopupTypeElc.statusChangeCallback(response); }); } $inloginPopupTypeElc.statusChangeCallback = function(response) { /*console.log("statusChangeCallback : ", response);*/ if (response.status === 'connected') { /*console.log("statusChangeCallback : if ", response);*/ } else { /*console.log("statusChangeCallback : else ", response);*/ } FB.login(function(response) { if (response.authResponse) { console.log("statusChangeCallback response.authResponse : ", response.authResponse); FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) { /*console.log('statusChangeCallback JSON : , ', JSON.stringify(response));*/ }); var accessToken = response.authResponse.accessToken; var user_id = response.authResponse.userID; var dataSend = { txt_fb_access_token: accessToken, }; /*console.log("statusChangeCallback : dataSend : ", dataSend);*/ UiCustomerBox.api.post("customer/facebook_login", dataSend).then(function(res) { /*console.log("customer/facebook_login : res", res);*/ if (res.ok == 1) { UiCustomerBox.callEventScript("on.justLogin", res.data); setTimeout(function() { $inloginPopupTypeElc.helper.pageUnLoad(); $inloginPopupTypeElc.close(); }, 100); UiCustomerBox.apiGetCustomerData(function() {}); /*location.reload();*/ /* RELOAD URL() */ } else { error.log('statusChangeCallback error.'); } }); } else { /*console.log('User cancelled login or did not fully authorize.');*/ } }, { scope: "email" }) } /* LoginFacebook */ /* Init */ /* Init */ /* Init */ $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { /* normal design */ case 405: $inloginPopupTypeElc.install(currentShopId, false); $inloginPopupTypeElc.installFacebook("000000000000000", "https://elctour.getappeasy.com/"); $inregisterPopupTypeElc.install(currentShopId, false); $inforgotpasswordPopupTypeElc.install(currentShopId, false); break; default: break; } });/* Cart displat at right side of page */ var $inloginPopupTypeGrip = {}; /* params */ $inloginPopupTypeGrip.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentLoginTypeGrip/"; $inloginPopupTypeGrip.templateRoot = 'root.php'; $inloginPopupTypeGrip.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inloginPopupTypeGrip.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inloginPopupTypeGrip.install = function(shopId, customBuild) { /* dont install in (checkout, login) */ this.templateRoot = 'root.php'; $.get($inloginPopupTypeGrip.path + 'componentLoginTypeGrip.css', function(response) { $('head').append(''); }); $.get($inloginPopupTypeGrip.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inloginPopupTypeGrip.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inloginPopupTypeGrip.windowFbAsyncInit = function(appId_in, status_in, xfbml_in, version_in) { window.fbAsyncInit = function() { FB.init({ appId: appId_in, status: status_in, xfbml: xfbml_in, version: version_in }); FB.getLoginStatus(function(response) { if (response.status === "connected") { /* alert("getLoginStatus : response.status : ", "connected"); */ var windowLocationHref = window.location.href; var check = "code="; if (windowLocationHref.indexOf(check) != -1) { $inloginPopupTypeGrip.checkLoginFacebook(response, function(statusChangeCallback) { if (statusChangeCallback) { window.location = encodeURI(encodeURI($inloginPopupTypeGrip.shop_domain)); /* location.reload(); */ } }); } } else { var status_login = UiCustomerBox.delegate.get.isLogin(); /* if (!status_login) { GAEAPI.get('customer/logout', {}).then(function(output_logout) { if (output_logout.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); } */ } }, true); /* FB.AppEvents.logPageView(); */ }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }; $inloginPopupTypeGrip.facebook_app_id = ''; $inloginPopupTypeGrip.shop_domain = ''; $inloginPopupTypeGrip.setInstallFacebook = function(facebook_app_id, shop_domain, callback) { var statu_install_facebook = false; if (facebook_app_id != "") { statu_install_facebook = true; $inloginPopupTypeGrip.windowFbAsyncInit(facebook_app_id, true, true, 'v3.1'); } callback(statu_install_facebook); }; $inloginPopupTypeGrip.checkLoginFacebook = function(response, callback) { $inloginPopupTypeGrip.statusChangeCallback(response, function(status_change_callback) { callback(status_change_callback); }); }; $inloginPopupTypeGrip.installFacebook = function(facebook_app_id, shop_domain) { $inloginPopupTypeGrip.setInstallFacebook(facebook_app_id, shop_domain, function(statu_install_facebook) { if (statu_install_facebook) { $inloginPopupTypeGrip.facebook_app_id = facebook_app_id; $inloginPopupTypeGrip.shop_domain = shop_domain; $inloginPopupTypeGrip.login.facebook = true; setTimeout(function() { FB.getLoginStatus(function(response) { if (response.status === "connected") { var windowLocationHref = window.location.href; var check = "code="; if (windowLocationHref.indexOf(check) != -1) { $inloginPopupTypeGrip.checkLoginFacebook(response, function(statusChangeCallback) { if (statusChangeCallback) { window.location = encodeURI(encodeURI($inloginPopupTypeGrip.shop_domain)); } }); } } }, true); }, 2000); } }); }; $inloginPopupTypeGrip.api = GURL.base_api_url(); /* Install */ /* login model */ $inloginPopupTypeGrip.getMe = {}; $inloginPopupTypeGrip.login = { email: '', password: '', remember: false, pressing: false, errore_mail: false, errore_password: false, facebook: false, twitter: false, google: false, }; $inloginPopupTypeGrip.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* login model */ /* validateLogin */ $inloginPopupTypeGrip.validateLogin = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inloginPopupTypeGrip.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inloginPopupTypeGrip.error.email = false; $inloginPopupTypeGrip.error.emailExist = false; $('#login-email-v1').css('border', ''); }, focusPassword: function() { $inloginPopupTypeGrip.error_password = false; $inloginPopupTypeGrip.error.wrong_password = false; $('#login-password-v1').css('border', ''); }, email: function() { var v = $('#login-email-v1').val(); var t = this; if (v.length <= 0) { $inloginPopupTypeGrip.shake(); $inloginPopupTypeGrip.validateLogin().emailInputNullError(); $inloginPopupTypeGrip.error_email = false; $inloginPopupTypeGrip.error_emailExist = false; return false; } else { var valid = $inloginPopupTypeGrip.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inloginPopupTypeGrip.shake(); $inloginPopupTypeGrip.validateLogin().emailInputError(); $inloginPopupTypeGrip.error_email = true; return false; } else if (v.length > 0 && valid) { $inloginPopupTypeGrip.validateLogin().emailOk(); return true; } } }, emailOk: function() { $('#login-email-v1').css('border', '2px solid green'); $inloginPopupTypeGrip.validateLogin().emailInputOk(); }, emailInputOk: function() { $("#login-error-email").removeClass("error"); $("#login-error-email").css('opacity', 0); }, emailError: function() { $("#login-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inloginPopupTypeGrip.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNotFoundError: function() { $inloginPopupTypeGrip.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ไม่พบอีเมลนี้ในข้อมูลสมาชิก Email is not found'); }, emailInputNullError: function() { $inloginPopupTypeGrip.validateLogin().emailError(); $("#login-error-email").addClass("error"); // $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#login-password-v1').val(); if (v.length <= 0) { $inloginPopupTypeGrip.validateLogin().passwordInputNullError(); $inloginPopupTypeGrip.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inloginPopupTypeGrip.error_password = false; /*$inloginPopupTypeGrip.validateLogin().passwordOk();*/ return true; } else if (v.length > 0 && v.length < 6) { $inloginPopupTypeGrip.error_password = true; $inloginPopupTypeGrip.shake(); $inloginPopupTypeGrip.validateLogin().passwordInputError(); return false; } }, passwordOk: function() { $("#login-password-v1").css('border', '2px solid green'); $inloginPopupTypeGrip.validateLogin().passwordInputOk(); }, passwordInputOk: function() { $("#login-error-password").removeClass("error"); $("#login-error-password").css('opacity', 0); }, passwordError: function() { $("#login-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inloginPopupTypeGrip.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputPasswordWrongError: function() { $inloginPopupTypeGrip.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('รหัสไม่ถูกต้อง Password is wrong'); }, passwordInputNullError: function() { $inloginPopupTypeGrip.validateLogin().passwordError(); $("#login-error-password").addClass("error"); // $("#login-error-password").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetEmail: function() { $("#login-email-v1").css('border', ''); $("#login-email-v1").val(''); $("#login-error-email").css('opacity', 0); }, resetPassword: function() { $("#login-password-v1").css('border', ''); $("#login-password-v1").val(''); $("#login-error-password").css('opacity', 0); }, reset: function() { $inloginPopupTypeGrip.validateLogin().resetEmail(); $inloginPopupTypeGrip.validateLogin().resetPassword(); }, }; return promise; }; /* validateLogin */ /* load html */ $inloginPopupTypeGrip.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inloginPopupTypeGrip.whenOnLoad = function(shopId) {}; $inloginPopupTypeGrip.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.login_vGrip_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.login_vGrip_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitLogin */ $inloginPopupTypeGrip.submitLogin = function() { $inloginPopupTypeGrip.login.email = $('#login-email-v1').val(); $inloginPopupTypeGrip.login.password = $('#login-password-v1').val(); var userEmail = $inloginPopupTypeGrip.login.email; var userPass = $inloginPopupTypeGrip.login.password; var userEmailValid = $inloginPopupTypeGrip.validateLogin().email(); var userPassValid = $inloginPopupTypeGrip.validateLogin().password(); console.log("submitLogin", "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); if (!userEmailValid || !userPassValid) { console.log("submitLogin", "return"); $inloginPopupTypeGrip.shake(); return; } $inloginPopupTypeGrip.validateLogin().checkEmail(userEmail, function(resultCheck) { console.log("submitLogin", resultCheck); if (resultCheck.ok == 1) { console.log('submitLogin true'); $inloginPopupTypeGrip.validateLogin().emailInputNotFoundError(); $inloginPopupTypeGrip.validateLogin().passwordInputPasswordWrongError(); $inloginPopupTypeGrip.error.email = true; $inloginPopupTypeGrip.error.emailExist = true; } else { console.log('submitLogin false'); return $inloginPopupTypeGrip.sendSubmitLogin(false); } }); }; /* submitLogin */ /* sendSubmitLogin */ $inloginPopupTypeGrip.sendSubmitLogin = function(reCheck) { $inloginPopupTypeGrip.login.pressing = true; var userEmail = $inloginPopupTypeGrip.login.email; var userPass = $inloginPopupTypeGrip.login.password; $inloginPopupTypeGrip.login.remember = $('#login-remember-v1')[0].checked; var userRemember = $inloginPopupTypeGrip.login.remember; console.log("sendSubmitLogin : userRemember : ", userRemember); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inloginPopupTypeGrip.validateLogin().emailInputError(); } else { $inloginPopupTypeGrip.validateLogin().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $inloginPopupTypeGrip.validateLogin().passwordOk(); } else { $inloginPopupTypeGrip.validateLogin().passwordInputError(); } /* email */ if (userEmail.length > 0 && !$inloginPopupTypeGrip.helper.isEmail(userEmail)) { $inloginPopupTypeGrip.error_email = true; } else { $inloginPopupTypeGrip.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inloginPopupTypeGrip.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inloginPopupTypeGrip.error_password = true; } if ($inloginPopupTypeGrip.error_password || $inloginPopupTypeGrip.error_email) { return; } } /* loading */ $inloginPopupTypeGrip.helper.pageLoad(); var token_login = {}; var hash_password = {}; var dataSendOne = { 'txt_email': userEmail }; var saveStorageData = {}; console.log("sendSubmitLogin : dataSendOne : ", dataSendOne); GAEAPI.post('customer/token_login', dataSendOne).then(function(e) { console.log("sendSubmitLogin : e : ", e); token_login = e.data; var dataSendTwo = { 'txt_password': userPass, 'txt_key_token': token_login.key_token, 'txt_secret_token': token_login.secret_token, }; GAEAPI.post('customer/generate_hash_password', dataSendTwo).then(function(ee) { hash_password = ee.data; var dataSendThree = { 'txt_email': userEmail, 'txt_hash_password': hash_password.hash_password }; saveStorageData.data_three = dataSendThree; GAEAPI.post('customer/login', dataSendThree).then(function(eee) { /* console.log("customer/login : done : ", eee); */ if (eee.ok == 1) { var data = GAEAPI.getValue(eee.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(data, cookie_key, ""); saveStorageData.gae_access_token = gae_access_token; if (userRemember) { /*console.log("login : setting cookie");*/ GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 24 * 360)); setTimeout(function() { $inloginPopupTypeGrip.helper.pageUnLoad(); $inloginPopupTypeGrip.close(); }, 100); } else { /* console.log("PressLogin -:- CookieLoginDestroy : "); */ console.log("PressLogin -:- CookieLoginDestroy : eee : ", eee); GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 3)); setTimeout(function() { $inloginPopupTypeGrip.helper.pageUnLoad(); $inloginPopupTypeGrip.close(); }, 100); $inloginPopupTypeGrip.getMe = eee.data; console.log("PressLogin -:- CookieLoginDestroy : getMe : ", $inloginPopupTypeGrip.getMe); UiCustomerBox.apiGetCustomerData(function() {}); /* location.reload(); */ /* RELOAD URL() */ } } else { $inloginPopupTypeGrip.helper.pageUnLoad(); setTimeout(function() { $inloginPopupTypeGrip.validateLogin().passwordInputError(); $inloginPopupTypeGrip.error.password = true; $inloginPopupTypeGrip.error.wrong_password = true; }, 500); } }); }); }); /* loading */ }; /* sendSubmitLogin */ /* viewPassword */ $inloginPopupTypeGrip.viewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); if (t === 'password') { e.setAttribute('type', 'text'); } else { e.setAttribute('type', 'password'); } return true; }; $inloginPopupTypeGrip.resetViewPassword = function(elementId) { try { var e = document.getElementById(elementId); var t = e.getAttribute('type'); e.setAttribute('type', 'password'); } catch (err) { console.log("inloginPopupTypeGrip : resetViewPassword : ", "error"); } return true; }; /* viewPassword */ $inloginPopupTypeGrip.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* loginSocialShow */ $inloginPopupTypeGrip.loginSocialShow = function() { /* $inloginPopupTypeGrip.login.facebook = face; $inloginPopupTypeGrip.login.twitter = twit; $inloginPopupTypeGrip.login.google = google; */ if (!$inloginPopupTypeGrip.login.facebook) { $('.form_large .facebook').css('display', 'none'); } else {} if (!$inloginPopupTypeGrip.login.twitter) { $('.form_large .twitter').css('display', 'none'); } else {} if (!$inloginPopupTypeGrip.login.google) { $('.form_large .google').css('display', 'none'); } else {} } /* Open */ var timerAdjustOpen = 0; $inloginPopupTypeGrip.isOpen = false; $inloginPopupTypeGrip.open = function() { $inloginPopupTypeGrip.loginSocialShow(); $inloginPopupTypeGrip.resetViewPassword('login-password-v1'); $inloginPopupTypeGrip.validateLogin().reset(); $(".login_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'relative' }); timerAdjustOpen = setTimeout(function() { $(".login.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inloginPopupTypeGrip.submitLogin(); } }); }; /* Open */ /* Close */ $inloginPopupTypeGrip.close = function() { $(".login_overlay").removeClass("is_open"); $(".login.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inloginPopupTypeGrip.shake = function() { $(".login.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".login.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* register */ $inloginPopupTypeGrip.register = function() { $inloginPopupTypeGrip.close(); $inregisterPopupTypeGrip.open(); } /* register */ /* register */ $inloginPopupTypeGrip.forgotpassword = function() { $inloginPopupTypeGrip.close(); $inforgotpasswordPopupTypeGrip.open(); } /* register */ $inloginPopupTypeGrip.statusChangeCallback = function(response, callback) { var status_change_callback = false; /* response.status : connected */ if (response.status === "connected") { /* FB.login(function(response) {}, { scope: 'email' }); */ /* alert("response.status : ", response.status); */ FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) {}); var dataSend = { txt_fb_access_token: response.authResponse.accessToken, }; UiCustomerBox.api.post("customer/facebook_login", dataSend).then(function(output) { if (output.ok == 1) { UiCustomerBox.callEventScript("on.justLogin", output.data); setTimeout(function() { $inloginPopupTypeGrip.helper.pageUnLoad(); $inloginPopupTypeGrip.close(); $inregisterPopupTypeGrip.close(); }, 100); UiCustomerBox.apiGetCustomerData(function() {}); } else {} status_change_callback = true; callback(status_change_callback); }); } /* response.status : not_authorized */ else if (response.status == "not_authorized") { window.location = encodeURI("https://www.facebook.com/v3.1/dialog/oauth?app_id=" + $inloginPopupTypeGrip.facebook_app_id + "&redirect_uri=" + encodeURI($inloginPopupTypeGrip.shop_domain) + "&scope=email"); callback(status_change_callback); } /* response.status : unknown */ else if (response.status == "unknown") { window.location = encodeURI("https://www.facebook.com/v3.1/dialog/oauth?app_id=" + $inloginPopupTypeGrip.facebook_app_id + "&redirect_uri=" + encodeURI($inloginPopupTypeGrip.shop_domain) + "&scope=email"); callback(status_change_callback); } }; /* LoginFacebook */ $inloginPopupTypeGrip.loginFacebook = function() { /*console.log("loginFacebook : loginFacebook ");*/ FB.getLoginStatus(function(response) { $inloginPopupTypeGrip.statusChangeCallback(response, function(status_change_callback) {}); }, true); }; /* LoginFacebook */ /* Init */ /* Init */ /* Init */ $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { /* normal design */ case 742: $inloginPopupTypeGrip.install(currentShopId, false); $inloginPopupTypeGrip.installFacebook("1267373963396891", "https://funfong.getappeasy.com/"); $inregisterPopupTypeGrip.install(currentShopId, false); $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; case 762: $inloginPopupTypeGrip.install(currentShopId, false); $inloginPopupTypeGrip.installFacebook("153794588908278", "https://griponline.net/"); $inregisterPopupTypeGrip.install(currentShopId, false); $inforgotpasswordPopupTypeGrip.install(currentShopId, false); break; default: break; } });/* Cart displat at right side of page */ var $inloginPopupTypeInfosat = {}; /* params */ $inloginPopupTypeInfosat.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentLoginTypeInfosat/"; $inloginPopupTypeInfosat.templateRoot = 'root.php'; $inloginPopupTypeInfosat.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inloginPopupTypeInfosat.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inloginPopupTypeInfosat.install = function(shopId, customBuild) { /* dont install in (checkout, login) */ this.templateRoot = 'root.php'; $.get($inloginPopupTypeInfosat.path + 'componentLoginTypeInfosat.css', function(response) { $('head').append(''); }); $.get($inloginPopupTypeInfosat.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inloginPopupTypeInfosat.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inloginPopupTypeInfosat.installFacebook = function(appID, Domain) { var facebook_js = "https://connect.facebook.net/en_US/sdk.js"; var facebookAppId = appID; /*console.log("installFacebook ", " Domain : ", Domain, " AppID : ", facebookAppId);*/ if (facebookAppId != "" && facebookAppId != undefined && facebookAppId != '000000000000000') { $inloginPopupTypeInfosat.login.facebook = true; window.fbAsyncInit = function() { FB.init({ appId: facebookAppId, cookie: true, xfbml: true, version: 'v2.8' }); FB.AppEvents.logPageView(); }; /* Load the SDK asynchronously */ (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = facebook_js; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); } else { $inloginPopupTypeInfosat.login.facebook = false; } }; $inloginPopupTypeInfosat.api = GURL.base_api_url(); /* Install */ /* login model */ $inloginPopupTypeInfosat.getMe = {}; $inloginPopupTypeInfosat.login = { email: '', password: '', remember: false, pressing: false, errore_mail: false, errore_password: false, facebook: false, twitter: false, google: false, }; $inloginPopupTypeInfosat.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* login model */ /* validateLogin */ $inloginPopupTypeInfosat.validateLogin = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inloginPopupTypeInfosat.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inloginPopupTypeInfosat.error.email = false; $inloginPopupTypeInfosat.error.emailExist = false; $('#login-email-v1').css('border', ''); }, focusPassword: function() { $inloginPopupTypeInfosat.error_password = false; $inloginPopupTypeInfosat.error.wrong_password = false; $('#login-password-v1').css('border', ''); }, email: function() { var v = $('#login-email-v1').val(); var t = this; if (v.length <= 0) { $inloginPopupTypeInfosat.shake(); $inloginPopupTypeInfosat.validateLogin().emailInputNullError(); $inloginPopupTypeInfosat.error_email = false; $inloginPopupTypeInfosat.error_emailExist = false; return false; } else { var valid = $inloginPopupTypeInfosat.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inloginPopupTypeInfosat.shake(); $inloginPopupTypeInfosat.validateLogin().emailInputError(); $inloginPopupTypeInfosat.error_email = true; return false; } else if (v.length > 0 && valid) { $inloginPopupTypeInfosat.validateLogin().emailOk(); return true; } } }, emailOk: function() { $('#login-email-v1').css('border', '2px solid green'); $inloginPopupTypeInfosat.validateLogin().emailInputOk(); }, emailInputOk: function() { $("#login-error-email").removeClass("error"); $("#login-error-email").css('opacity', 0); }, emailError: function() { $("#login-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inloginPopupTypeInfosat.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNotFoundError: function() { $inloginPopupTypeInfosat.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ไม่พบอีเมลนี้ในข้อมูลสมาชิก Email is not found'); }, emailInputNullError: function() { $inloginPopupTypeInfosat.validateLogin().emailError(); $("#login-error-email").addClass("error"); // $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#login-password-v1').val(); if (v.length <= 0) { $inloginPopupTypeInfosat.validateLogin().passwordInputNullError(); $inloginPopupTypeInfosat.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inloginPopupTypeInfosat.error_password = false; /*$inloginPopupTypeInfosat.validateLogin().passwordOk();*/ return true; } else if (v.length > 0 && v.length < 6) { $inloginPopupTypeInfosat.error_password = true; $inloginPopupTypeInfosat.shake(); $inloginPopupTypeInfosat.validateLogin().passwordInputError(); return false; } }, passwordOk: function() { $("#login-password-v1").css('border', '2px solid green'); $inloginPopupTypeInfosat.validateLogin().passwordInputOk(); }, passwordInputOk: function() { $("#login-error-password").removeClass("error"); $("#login-error-password").css('opacity', 0); }, passwordError: function() { $("#login-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inloginPopupTypeInfosat.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputPasswordWrongError: function() { $inloginPopupTypeInfosat.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('รหัสไม่ถูกต้อง Password is wrong'); }, passwordInputNullError: function() { $inloginPopupTypeInfosat.validateLogin().passwordError(); $("#login-error-password").addClass("error"); // $("#login-error-password").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetEmail: function() { $("#login-email-v1").css('border', ''); $("#login-email-v1").val(''); $("#login-error-email").css('opacity', 0); }, resetPassword: function() { $("#login-password-v1").css('border', ''); $("#login-password-v1").val(''); $("#login-error-password").css('opacity', 0); }, reset: function() { $inloginPopupTypeInfosat.validateLogin().resetEmail(); $inloginPopupTypeInfosat.validateLogin().resetPassword(); }, }; return promise; }; /* validateLogin */ /* load html */ $inloginPopupTypeInfosat.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inloginPopupTypeInfosat.whenOnLoad = function(shopId) {}; $inloginPopupTypeInfosat.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.login_vInfosat_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.login_vInfosat_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitLogin */ $inloginPopupTypeInfosat.submitLogin = function() { $inloginPopupTypeInfosat.login.email = $('#login-email-v1').val(); $inloginPopupTypeInfosat.login.password = $('#login-password-v1').val(); var userEmail = $inloginPopupTypeInfosat.login.email; var userPass = $inloginPopupTypeInfosat.login.password; var userEmailValid = $inloginPopupTypeInfosat.validateLogin().email(); var userPassValid = $inloginPopupTypeInfosat.validateLogin().password(); console.log("submitLogin", "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); if (!userEmailValid || !userPassValid) { console.log("submitLogin", "return"); $inloginPopupTypeInfosat.shake(); return; } $inloginPopupTypeInfosat.validateLogin().checkEmail(userEmail, function(resultCheck) { console.log("submitLogin", resultCheck); if (resultCheck.ok == 1) { console.log('submitLogin true'); $inloginPopupTypeInfosat.validateLogin().emailInputNotFoundError(); $inloginPopupTypeInfosat.validateLogin().passwordInputPasswordWrongError(); $inloginPopupTypeInfosat.error.email = true; $inloginPopupTypeInfosat.error.emailExist = true; } else { console.log('submitLogin false'); return $inloginPopupTypeInfosat.sendSubmitLogin(false); } }); }; /* submitLogin */ /* sendSubmitLogin */ $inloginPopupTypeInfosat.sendSubmitLogin = function(reCheck) { $inloginPopupTypeInfosat.login.pressing = true; var userEmail = $inloginPopupTypeInfosat.login.email; var userPass = $inloginPopupTypeInfosat.login.password; $inloginPopupTypeInfosat.login.remember = $('#login-remember-v1')[0].checked; var userRemember = $inloginPopupTypeInfosat.login.remember; console.log("sendSubmitLogin : userRemember : ", userRemember); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inloginPopupTypeInfosat.validateLogin().emailInputError(); } else { $inloginPopupTypeInfosat.validateLogin().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $inloginPopupTypeInfosat.validateLogin().passwordOk(); } else { $inloginPopupTypeInfosat.validateLogin().passwordInputError(); } /* email */ if (userEmail.length > 0 && !$inloginPopupTypeInfosat.helper.isEmail(userEmail)) { $inloginPopupTypeInfosat.error_email = true; } else { $inloginPopupTypeInfosat.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inloginPopupTypeInfosat.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inloginPopupTypeInfosat.error_password = true; } if ($inloginPopupTypeInfosat.error_password || $inloginPopupTypeInfosat.error_email) { return; } } /* loading */ $inloginPopupTypeInfosat.helper.pageLoad(); var token_login = {}; var hash_password = {}; var dataSendOne = { 'txt_email': userEmail }; var saveStorageData = {}; console.log("sendSubmitLogin : dataSendOne : ", dataSendOne); GAEAPI.post('customer/token_login', dataSendOne).then(function(e) { console.log("sendSubmitLogin : e : ", e); token_login = e.data; var dataSendTwo = { 'txt_password': userPass, 'txt_key_token': token_login.key_token, 'txt_secret_token': token_login.secret_token, }; GAEAPI.post('customer/generate_hash_password', dataSendTwo).then(function(ee) { hash_password = ee.data; var dataSendThree = { 'txt_email': userEmail, 'txt_hash_password': hash_password.hash_password }; saveStorageData.data_three = dataSendThree; GAEAPI.post('customer/login', dataSendThree).then(function(eee) { /* console.log("customer/login : done : ", eee); */ if (eee.ok == 1) { var data = GAEAPI.getValue(eee.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(data, cookie_key, ""); saveStorageData.gae_access_token = gae_access_token; if (userRemember) { /*console.log("login : setting cookie");*/ GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 24 * 360)); setTimeout(function() { $inloginPopupTypeInfosat.helper.pageUnLoad(); $inloginPopupTypeInfosat.close(); location.reload(); }, 100); } else { /* console.log("PressLogin -:- CookieLoginDestroy : "); */ console.log("PressLogin -:- CookieLoginDestroy : eee : ", eee); GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 3)); setTimeout(function() { $inloginPopupTypeInfosat.helper.pageUnLoad(); $inloginPopupTypeInfosat.close(); location.reload(); }, 100); $inloginPopupTypeInfosat.getMe = eee.data; console.log("PressLogin -:- CookieLoginDestroy : getMe : ", $inloginPopupTypeInfosat.getMe); UiCustomerBox.apiGetCustomerData(function() {}); location.reload(); /* location.reload(); */ /* RELOAD URL() */ } } else { $inloginPopupTypeInfosat.helper.pageUnLoad(); setTimeout(function() { $inloginPopupTypeInfosat.validateLogin().passwordInputError(); $inloginPopupTypeInfosat.error.password = true; $inloginPopupTypeInfosat.error.wrong_password = true; }, 500); } }); }); }); /* loading */ }; /* sendSubmitLogin */ /* viewPassword */ $inloginPopupTypeInfosat.viewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); if (t === 'password') { e.setAttribute('type', 'text'); } else { e.setAttribute('type', 'password'); } return true; }; $inloginPopupTypeInfosat.resetViewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); e.setAttribute('type', 'password'); return true; }; /* viewPassword */ $inloginPopupTypeInfosat.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* loginSocialShow */ $inloginPopupTypeInfosat.loginSocialShow = function() { /* $inloginPopupTypeInfosat.login.facebook = face; $inloginPopupTypeInfosat.login.twitter = twit; $inloginPopupTypeInfosat.login.google = google; */ if (!$inloginPopupTypeInfosat.login.facebook) { $('.form_large .facebook').css('display', 'none'); } else {} if (!$inloginPopupTypeInfosat.login.twitter) { $('.form_large .twitter').css('display', 'none'); } else {} if (!$inloginPopupTypeInfosat.login.google) { $('.form_large .google').css('display', 'none'); } else {} } /* Open */ var timerAdjustOpen = 0; $inloginPopupTypeInfosat.isOpen = false; $inloginPopupTypeInfosat.open = function() { $inloginPopupTypeInfosat.loginSocialShow(); $inloginPopupTypeInfosat.resetViewPassword('login-password-v1'); $inloginPopupTypeInfosat.validateLogin().reset(); $(".login_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden', }); $('body').css({ 'overflow': 'hidden', 'position': 'fixed' }); timerAdjustOpen = setTimeout(function() { $(".login.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inloginPopupTypeInfosat.submitLogin(); } }); }; /* Open */ /* Close */ $inloginPopupTypeInfosat.close = function() { $(".login_overlay").removeClass("is_open"); $(".login.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inloginPopupTypeInfosat.shake = function() { $(".login.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".login.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* register */ $inloginPopupTypeInfosat.register = function() { $inloginPopupTypeInfosat.close(); $inregisterPopupTypeInfosat.open(); } /* register */ /* register */ $inloginPopupTypeInfosat.forgotpassword = function() { $inloginPopupTypeInfosat.close(); $inforgotpasswordPopupTypeInfosat.open() } /* register */ /* LoginFacebook */ $inloginPopupTypeInfosat.loginFacebook = function() { /*console.log("loginFacebook : loginFacebook ");*/ FB.getLoginStatus(function(response) { $inloginPopupTypeInfosat.statusChangeCallback(response); }); } $inloginPopupTypeInfosat.statusChangeCallback = function(response) { /*console.log("statusChangeCallback : ", response);*/ if (response.status === 'connected') { /*console.log("statusChangeCallback : if ", response);*/ } else { /*console.log("statusChangeCallback : else ", response);*/ } FB.login(function(response) { if (response.authResponse) { console.log("statusChangeCallback response.authResponse : ", response.authResponse); FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) { /*console.log('statusChangeCallback JSON : , ', JSON.stringify(response));*/ }); var accessToken = response.authResponse.accessToken; var user_id = response.authResponse.userID; var dataSend = { txt_fb_access_token: accessToken, }; /*console.log("statusChangeCallback : dataSend : ", dataSend);*/ UiCustomerBox.api.post("customer/facebook_login", dataSend).then(function(res) { /*console.log("customer/facebook_login : res", res);*/ if (res.ok == 1) { UiCustomerBox.callEventScript("on.justLogin", res.data); setTimeout(function() { $inloginPopupTypeInfosat.helper.pageUnLoad(); $inloginPopupTypeInfosat.close(); }, 100); UiCustomerBox.apiGetCustomerData(function() {}); /*location.reload();*/ /* RELOAD URL() */ } else { error.log('statusChangeCallback error.'); } }); } else { /*console.log('User cancelled login or did not fully authorize.');*/ } }, { scope: "email" }) } /* LoginFacebook */ /* Init */ /* Init */ /* Init */ $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { /* normal design */ case 754: $inloginPopupTypeInfosat.install(currentShopId, true); $inloginPopupTypeInfosat.installFacebook("", "https://infosat.getappeasy.com/"); $inregisterPopupTypeInfosat.install(currentShopId, false); $inforgotpasswordPopupTypeInfosat.install(currentShopId, false); break; default: break; } });/* Cart displat at right side of page */ var $inloginPopupTypeProin = {}; /* params */ $inloginPopupTypeProin.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentLoginTypeProin/"; $inloginPopupTypeProin.templateRoot = 'root.php'; $inloginPopupTypeProin.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inloginPopupTypeProin.indexCout = 0; $inloginPopupTypeProin.reload = false; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inloginPopupTypeProin.install = function(shopId, logo, customBuild, reload) { $inloginPopupTypeProin.reload = reload; var logoin = logo; /* dont install in (checkout, login) */ this.templateRoot = 'root.php'; $.get($inloginPopupTypeProin.path + 'componentLoginTypeProin.css', function(response) { $('head').append(''); }); $.get($inloginPopupTypeProin.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, logo: logoin, custom: customBuild, path: $inloginPopupTypeProin.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; /* Install */ /* installFacebook */ $inloginPopupTypeProin.windowFbAsyncInit = function(appId_in, status_in, xfbml_in, version_in) { $inloginPopupTypeProin.displayView().consoleLog("windowFbAsyncInit : appId_in : ", appId_in); $inloginPopupTypeProin.displayView().consoleLog("windowFbAsyncInit : status_in : ", status_in); $inloginPopupTypeProin.displayView().consoleLog("windowFbAsyncInit : xfbml_in : ", xfbml_in); $inloginPopupTypeProin.displayView().consoleLog("windowFbAsyncInit : version_in : ", version_in); window.fbAsyncInit = function() { FB.init({ appId: appId_in, status: status_in, /* cookie: cookie_in, */ xfbml: xfbml_in, version: version_in }); FB.getLoginStatus(function(response) { $inloginPopupTypeProin.displayView().consoleLog("getLoginStatus : response.status : ", response.status); if (response.status === "connected") { /* alert("getLoginStatus : response.status : ", "connected"); */ var windowLocationHref = window.location.href; var check = "code="; if (windowLocationHref.indexOf(check) != -1) { $inloginPopupTypeProin.checkLoginFacebook(response, function(statusChangeCallback) { $inloginPopupTypeProin.displayView().consoleLog("windowFbAsyncInit : checkLoginFacebook : statusChangeCallback : ", statusChangeCallback); if (statusChangeCallback) { window.location = encodeURI(encodeURI($inloginPopupTypeProin.shop_domain)); /* location.reload(); */ } }); } } else { var status_login = UiCustomerBox.delegate.get.isLogin(); $inloginPopupTypeProin.displayView().consoleLog("windowFbAsyncInit : status_login : ", status_login); /* if (!status_login) { GAEAPI.get('customer/logout', {}).then(function(output_logout) { if (output_logout.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); } */ } }, true); /* FB.AppEvents.logPageView(); */ }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); }; $inloginPopupTypeProin.facebook_app_id = ''; $inloginPopupTypeProin.shop_domain = ''; $inloginPopupTypeProin.setInstallFacebook = function(facebook_app_id, shop_domain, callback) { $inloginPopupTypeProin.displayView().consoleLog("setInstallFacebook : facebook_app_id : ", facebook_app_id); $inloginPopupTypeProin.displayView().consoleLog("setInstallFacebook : shop_domain : ", shop_domain); var statu_install_facebook = false; if (facebook_app_id != "") { statu_install_facebook = true; $inloginPopupTypeProin.windowFbAsyncInit(facebook_app_id, true, true, 'v3.1'); } callback(statu_install_facebook); }; /*---------------------------*/ $inloginPopupTypeProin.checkLoginFacebook = function(response, callback) { $inloginPopupTypeProin.statusChangeCallback(response, function(status_change_callback) { $inloginPopupTypeProin.displayView().consoleLog("checkLoginFacebook : statusChangeCallback : status_change_callback : ", status_change_callback); callback(status_change_callback); }); }; $inloginPopupTypeProin.statusChangeCallback = function(response, callback) { $inloginPopupTypeProin.displayView().consoleLog("status_change_callback : response : ", response); $inloginPopupTypeProin.displayView().consoleLog("statusChangeCallback : response.status : ", response.status); var status_change_callback = false; /* response.status : connected */ if (response.status === "connected") { /* FB.login(function(response) {}, { scope: 'email' }); */ /* alert("response.status : ", response.status); */ FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) { $inloginPopupTypeProin.displayView().consoleLog("statusChangeCallback : connected : FB.api : response : ", response); }); $inloginPopupTypeProin.displayView().consoleLog("statusChangeCallback : connected : response : ", response); var dataSend = { txt_fb_access_token: response.authResponse.accessToken, }; $inloginPopupTypeProin.displayView().consoleLog("statusChangeCallback : connected : dataSend : ", dataSend); UiCustomerBox.api.post("customer/facebook_login", dataSend).then(function(output) { $inloginPopupTypeProin.displayView().consoleLog("statusChangeCallback : connected : UiCustomerBox : output : ", output); if (output.ok == 1) { $inloginPopupTypeProin.displayView().consoleLog("statusChangeCallback : connected : UiCustomerBox : output : ", "PASS"); UiCustomerBox.callEventScript("on.justLogin", output.data); setTimeout(function() { $inloginPopupTypeProin.helper.pageUnLoad(); $inloginPopupTypeProin.close(); $inregisterPopupTypeProin.close(); }, 100); UiCustomerBox.apiGetCustomerData(function() {}); } else { $inloginPopupTypeProin.displayView().consoleLog("statusChangeCallback : connected : UiCustomerBox : output : ", "ERROR"); } status_change_callback = true; callback(status_change_callback); }); } /* response.status : not_authorized */ else if (response.status == "not_authorized") { window.location = encodeURI("https://www.facebook.com/v3.1/dialog/oauth?app_id=" + $inloginPopupTypeProin.facebook_app_id + "&redirect_uri=" + encodeURI($inloginPopupTypeProin.shop_domain) + "&scope=email"); callback(status_change_callback); } /* response.status : unknown */ else if (response.status == "unknown") { window.location = encodeURI("https://www.facebook.com/v3.1/dialog/oauth?app_id=" + $inloginPopupTypeProin.facebook_app_id + "&redirect_uri=" + encodeURI($inloginPopupTypeProin.shop_domain) + "&scope=email"); callback(status_change_callback); } }; $inloginPopupTypeProin.loginFacebook = function() { $inloginPopupTypeProin.displayView().consoleLog("loginFacebook : statu : ", "start"); FB.getLoginStatus(function(response) { $inloginPopupTypeProin.displayView().consoleLog("loginFacebook : getLoginStatus : response : ", response); $inloginPopupTypeProin.statusChangeCallback(response, function(status_change_callback) { $inloginPopupTypeProin.displayView().consoleLog("loginFacebook : statusChangeCallback : status_change_callback : ", status_change_callback); }); }, true); }; /*---------------------------*/ $inloginPopupTypeProin.installFacebook = function(facebook_app_id, shop_domain) { $inloginPopupTypeProin.displayView().consoleLog("installFacebook : facebook_app_id : ", facebook_app_id); $inloginPopupTypeProin.displayView().consoleLog("installFacebook : shop_domain : ", shop_domain); $inloginPopupTypeProin.setInstallFacebook(facebook_app_id, shop_domain, function(statu_install_facebook) { $inloginPopupTypeProin.displayView().consoleLog("installFacebook : setInstallFacebook : statu_install_facebook : ", statu_install_facebook); if (statu_install_facebook) { $inloginPopupTypeProin.facebook_app_id = facebook_app_id; $inloginPopupTypeProin.shop_domain = shop_domain; $inloginPopupTypeProin.login.facebook = true; setTimeout(function() { try { FB.getLoginStatus(function(response) { $inloginPopupTypeProin.displayView().consoleLog("getLoginStatus : response.status : ", response.status); if (response.status === "connected") { var windowLocationHref = window.location.href; var check = "code="; if (windowLocationHref.indexOf(check) != -1) { $inloginPopupTypeProin.checkLoginFacebook(response, function(statusChangeCallback) { $inloginPopupTypeProin.displayView().consoleLog("installFacebook : checkLoginFacebook : statusChangeCallback : ", statusChangeCallback); if (statusChangeCallback) { window.location = encodeURI(encodeURI($inloginPopupTypeProin.shop_domain)); } }); } } }, true); } catch (err) { $inloginPopupTypeProin.displayView().consoleLog("getLoginStatus : response.status : ", "error"); } }, 1500); } }); }; /* installFacebook */ /* displayView */ $inloginPopupTypeProin.displayView = function() { var display = { consoleLog: function(statu, data) { var statuConsole = true; if (statuConsole) { console.log(statu, data); } }, }; return display; }; /* displayView */ /* login model */ $inloginPopupTypeProin.getMe = {}; $inloginPopupTypeProin.login = { email: '', password: '', remember: false, pressing: false, errore_mail: false, errore_password: false, facebook: false, twitter: false, google: false, }; $inloginPopupTypeProin.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* login model */ /* validateLogin */ $inloginPopupTypeProin.validateLogin = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inloginPopupTypeProin.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inloginPopupTypeProin.error.email = false; $inloginPopupTypeProin.error.emailExist = false; $('#login-email-v1').css('border', ''); }, focusPassword: function() { $inloginPopupTypeProin.error_password = false; $inloginPopupTypeProin.error.wrong_password = false; $('#login-password-v1').css('border', ''); }, email: function() { var v = $('#login-email-v1').val(); var t = this; if (v.length <= 0) { $inloginPopupTypeProin.shake(); $inloginPopupTypeProin.validateLogin().emailInputNullError(); $inloginPopupTypeProin.error_email = false; $inloginPopupTypeProin.error_emailExist = false; return false; } else { var valid = $inloginPopupTypeProin.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inloginPopupTypeProin.shake(); $inloginPopupTypeProin.validateLogin().emailInputError(); $inloginPopupTypeProin.error_email = true; return false; } else if (v.length > 0 && valid) { $inloginPopupTypeProin.validateLogin().emailOk(); return true; } } }, emailOk: function() { $('#login-email-v1').css('border', '2px solid green'); $inloginPopupTypeProin.validateLogin().emailInputOk(); }, emailInputOk: function() { $("#login-error-email").removeClass("error"); $("#login-error-email").css('opacity', 0); }, emailError: function() { $("#login-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inloginPopupTypeProin.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล Email should be valid'); }, emailInputNotFoundError: function() { $inloginPopupTypeProin.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ไม่พบอีเมลนี้ในข้อมูลสมาชิก Email is not found'); }, emailInputNullError: function() { $inloginPopupTypeProin.validateLogin().emailError(); $("#login-error-email").addClass("error"); // $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#login-password-v1').val(); if (v.length <= 0) { $inloginPopupTypeProin.validateLogin().passwordInputNullError(); $inloginPopupTypeProin.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inloginPopupTypeProin.error_password = false; /*$inloginPopupTypeProin.validateLogin().passwordOk();*/ return true; } else if (v.length > 0 && v.length < 6) { $inloginPopupTypeProin.error_password = true; $inloginPopupTypeProin.shake(); $inloginPopupTypeProin.validateLogin().passwordInputError(); return false; } }, passwordOk: function() { $("#login-password-v1").css('border', '2px solid green'); $inloginPopupTypeProin.validateLogin().passwordInputOk(); }, passwordInputOk: function() { $("#login-error-password").removeClass("error"); $("#login-error-password").css('opacity', 0); }, passwordError: function() { $("#login-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inloginPopupTypeProin.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputPasswordWrongError: function() { $inloginPopupTypeProin.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('รหัสไม่ถูกต้อง Password is wrong'); }, passwordInputNullError: function() { $inloginPopupTypeProin.validateLogin().passwordError(); $("#login-error-password").addClass("error"); // $("#login-error-password").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetEmail: function() { $("#login-email-v1").css('border', ''); $("#login-email-v1").val(''); $("#login-error-email").css('opacity', 0); }, resetPassword: function() { $("#login-password-v1").css('border', ''); $("#login-password-v1").val(''); $("#login-error-password").css('opacity', 0); }, reset: function() { $inloginPopupTypeProin.validateLogin().resetEmail(); $inloginPopupTypeProin.validateLogin().resetPassword(); }, }; return promise; }; /* validateLogin */ /* load html */ $inloginPopupTypeProin.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inloginPopupTypeProin.whenOnLoad = function(shopId) {}; $inloginPopupTypeProin.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.login_v1_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.login_v1_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitLogin */ $inloginPopupTypeProin.submitLogin = function() { $inloginPopupTypeProin.login.email = $('#login-email-v1').val(); $inloginPopupTypeProin.login.password = $('#login-password-v1').val(); var userEmail = $inloginPopupTypeProin.login.email; var userPass = $inloginPopupTypeProin.login.password; var userEmailValid = $inloginPopupTypeProin.validateLogin().email(); var userPassValid = $inloginPopupTypeProin.validateLogin().password(); console.log("submitLogin", "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); if (!userEmailValid || !userPassValid) { console.log("submitLogin", "return"); $inloginPopupTypeProin.shake(); return; } $inloginPopupTypeProin.validateLogin().checkEmail(userEmail, function(resultCheck) { console.log("submitLogin", resultCheck); if (resultCheck.ok == 1) { console.log('submitLogin true'); $inloginPopupTypeProin.validateLogin().emailInputNotFoundError(); $inloginPopupTypeProin.validateLogin().passwordInputPasswordWrongError(); $inloginPopupTypeProin.error.email = true; $inloginPopupTypeProin.error.emailExist = true; } else { console.log('submitLogin false'); return $inloginPopupTypeProin.sendSubmitLogin(false); } }); }; /* submitLogin */ /* sendSubmitLogin */ $inloginPopupTypeProin.sendSubmitLogin = function(reCheck) { $inloginPopupTypeProin.login.pressing = true; var userEmail = $inloginPopupTypeProin.login.email; var userPass = $inloginPopupTypeProin.login.password; // $inloginPopupTypeProin.login.remember = $('#login-remember-v1')[0].checked; var userRemember = $inloginPopupTypeProin.login.remember; console.log("sendSubmitLogin : userRemember", userRemember); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inloginPopupTypeProin.validateLogin().emailInputError(); } else { $inloginPopupTypeProin.validateLogin().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $inloginPopupTypeProin.validateLogin().passwordOk(); } else { $inloginPopupTypeProin.validateLogin().passwordInputError(); } /* email */ if (userEmail.length > 0 && !$inloginPopupTypeProin.helper.isEmail(userEmail)) { $inloginPopupTypeProin.error_email = true; } else { $inloginPopupTypeProin.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inloginPopupTypeProin.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inloginPopupTypeProin.error_password = true; } if ($inloginPopupTypeProin.error_password || $inloginPopupTypeProin.error_email) { return; } } /* loading */ $inloginPopupTypeProin.helper.pageLoad(); var token_login = {}; var hash_password = {}; var dataSendOne = { 'txt_email': userEmail }; var saveStorageData = {}; console.log("sendSubmitLogin : dataSendOne : ", dataSendOne); GAEAPI.post('customer/token_login', dataSendOne).then(function(e) { console.log("sendSubmitLogin : GAEAPI.post : e : ", e); token_login = e.data; var dataSendTwo = { 'txt_password': userPass, 'txt_key_token': token_login.key_token, 'txt_secret_token': token_login.secret_token, }; /* console.log("sendSubmitLogin : dataSendTwo", dataSendTwo); */ GAEAPI.post('customer/generate_hash_password', dataSendTwo).then(function(ee) { console.log("sendSubmitLogin : GAEAPI.post : ee : ", ee); hash_password = ee.data; var dataSendThree = { 'txt_email': userEmail, 'txt_hash_password': hash_password.hash_password }; /* console.log("sendSubmitLogin : dataSendThree : ", dataSendThree); */ saveStorageData.data_three = dataSendThree; GAEAPI.post('customer/login', dataSendThree).then(function(eee) { /* console.log("sendSubmitLogin : GAEAPI.post : eee : ", eee); */ /*console.log("login : done", eee);*/ if (eee.ok == 1) { var data = GAEAPI.getValue(eee.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(data, cookie_key, ""); saveStorageData.gae_access_token = gae_access_token; if (userRemember) { /*console.log("login : setting cookie");*/ GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 24 * 360)); setTimeout(function() { $inloginPopupTypeProin.helper.pageUnLoad(); $inloginPopupTypeProin.close(); }, 100); if ($inloginPopupTypeProin.reload) { location.reload(); } } else { /* console.log("PressLogin -:- CookieLoginDestroy : "); */ console.log("PressLogin -:- CookieLoginDestroy : eee : ", eee); GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 3)); setTimeout(function() { $inloginPopupTypeProin.helper.pageUnLoad(); $inloginPopupTypeProin.close(); }, 100); $inloginPopupTypeProin.getMe = eee.data; console.log("PressLogin -:- CookieLoginDestroy : getMe : ", $inloginPopupTypeProin.getMe); UiCustomerBox.apiGetCustomerData(function() {}); if ($inloginPopupTypeProin.reload) { location.reload(); } /* location.reload(); */ /* RELOAD URL() */ } } else { $inloginPopupTypeProin.helper.pageUnLoad(); setTimeout(function() { $inloginPopupTypeProin.validateLogin().passwordInputPasswordWrongError(); $inloginPopupTypeProin.error.password = true; $inloginPopupTypeProin.error.wrong_password = true; }, 500); } }); }); }); /* loading */ }; /* sendSubmitLogin */ /* viewPassword */ $inloginPopupTypeProin.viewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); if (t === 'password') { e.setAttribute('type', 'text'); } else { e.setAttribute('type', 'password'); } return true; }; $inloginPopupTypeProin.resetViewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); e.setAttribute('type', 'password'); return true; }; /* viewPassword */ $inloginPopupTypeProin.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* loginSocialShow */ $inloginPopupTypeProin.loginSocialShow = function() { /* $inloginPopupTypeProin.login.facebook = face; $inloginPopupTypeProin.login.twitter = twit; $inloginPopupTypeProin.login.google = google; */ if (!$inloginPopupTypeProin.login.facebook) { $('.heading.top_social').css('display', 'none'); $('.cover_from .login.from_background').css('height', 'auto'); $('.form_large .facebook').css('display', 'none'); } else {} if (!$inloginPopupTypeProin.login.twitter) { $('.form_large .twitter').css('display', 'none'); } else {} if (!$inloginPopupTypeProin.login.google) { $('.form_large .google').css('display', 'none'); } else {} } /* Open */ var timerAdjustOpen = 0; $inloginPopupTypeProin.isOpen = false; $inloginPopupTypeProin.open = function() { $inloginPopupTypeProin.loginSocialShow(); $inloginPopupTypeProin.resetViewPassword('login-password-v1'); $inloginPopupTypeProin.validateLogin().reset(); $(".login_overlay").addClass("is_open"); $('body').css({ 'overflow': 'hidden', 'height': '100%' }); timerAdjustOpen = setTimeout(function() { $(".login.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inloginPopupTypeProin.submitLogin(); } }); }; /* Open */ /* Close */ $inloginPopupTypeProin.close = function() { $(".login_overlay").removeClass("is_open"); $(".login.from_background").removeClass("is_open"); $('body').css({ 'overflow': 'auto' }); }; /* Close */ /* shake */ $inloginPopupTypeProin.shake = function() { $(".login.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".login.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* register */ $inloginPopupTypeProin.register = function() { $inloginPopupTypeProin.close(); $inregisterPopupTypeProin.open(); } /* register */ /* register */ $inloginPopupTypeProin.forgotpassword = function() { $inloginPopupTypeProin.close(); $inforgotpasswordPopupTypeProin.open() } /* register */ /* Init */ /* Init */ /* Init */ $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { /* normal design */ case 495: $inloginPopupTypeProin.install(currentShopId, 'https://image.getappeasy.com/src/images/2000/1210/0876/210876t1535041956.png', false, false); $inloginPopupTypeProin.installFacebook("2107006032885166", "https://proplugin.com/"); $inregisterPopupTypeProin.install(currentShopId, 'https://image.getappeasy.com/src/images/2000/1210/0876/210876t1535041956.png', false); $inforgotpasswordPopupTypeProin.install(currentShopId, 'https://image.getappeasy.com/src/images/2000/1210/0876/210876t1535041956.png', false); break; default: break; } });/* Cart displat at right side of page */ var $inloginPopupTypeSirikhu = {}; /* params */ $inloginPopupTypeSirikhu.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentLoginTypeSirikhun/"; $inloginPopupTypeSirikhu.templateRoot = 'root.php'; $inloginPopupTypeSirikhu.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inloginPopupTypeSirikhu.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inloginPopupTypeSirikhu.install = function(shopId, customBuild) { /* dont install in (checkout, login) */ this.templateRoot = 'root.php'; $.get($inloginPopupTypeSirikhu.path + 'componentLoginTypeSirikhun.css', function(response) { $('head').append(''); }); $.get($inloginPopupTypeSirikhu.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inloginPopupTypeSirikhu.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inloginPopupTypeSirikhu.installFacebook = function(appID, Domain) { var facebook_js = "https://connect.facebook.net/en_US/sdk.js"; var facebookAppId = appID; /*console.log("installFacebook ", " Domain : ", Domain, " AppID : ", facebookAppId);*/ if (facebookAppId != "" && facebookAppId != undefined && facebookAppId != '000000000000000') { $inloginPopupTypeSirikhu.login.facebook = true; window.fbAsyncInit = function() { FB.init({ appId: facebookAppId, cookie: true, xfbml: true, version: 'v2.8' }); FB.AppEvents.logPageView(); }; /* Load the SDK asynchronously */ (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = facebook_js; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); } else { $inloginPopupTypeSirikhu.login.facebook = false; } }; $inloginPopupTypeSirikhu.api = GURL.base_api_url(); /* Install */ /* login model */ $inloginPopupTypeSirikhu.getMe = {}; $inloginPopupTypeSirikhu.login = { email: '', password: '', remember: false, pressing: false, errore_mail: false, errore_password: false, facebook: false, twitter: false, google: false, }; $inloginPopupTypeSirikhu.error = { emailExist: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* login model */ /* validateLogin */ $inloginPopupTypeSirikhu.validateLogin = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inloginPopupTypeSirikhu.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusEmail: function() { $inloginPopupTypeSirikhu.error.email = false; $inloginPopupTypeSirikhu.error.emailExist = false; $('#login-email-v1').css('border', ''); }, focusPassword: function() { $inloginPopupTypeSirikhu.error_password = false; $inloginPopupTypeSirikhu.error.wrong_password = false; $('#login-password-v1').css('border', ''); }, email: function() { var v = $('#login-email-v1').val(); var t = this; if (v.length <= 0) { $inloginPopupTypeSirikhu.shake(); $inloginPopupTypeSirikhu.validateLogin().emailInputNullError(); $inloginPopupTypeSirikhu.error_email = false; $inloginPopupTypeSirikhu.error_emailExist = false; return false; } else { var valid = $inloginPopupTypeSirikhu.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inloginPopupTypeSirikhu.shake(); $inloginPopupTypeSirikhu.validateLogin().emailInputError(); $inloginPopupTypeSirikhu.error_email = true; return false; } else if (v.length > 0 && valid) { $inloginPopupTypeSirikhu.validateLogin().emailOk(); return true; } } }, emailOk: function() { $('#login-email-v1').css('border', '2px solid green'); $inloginPopupTypeSirikhu.validateLogin().emailInputOk(); }, emailInputOk: function() { $("#login-error-email").removeClass("error"); $("#login-error-email").css('opacity', 0); }, emailError: function() { $("#login-email-v1").css('border', '2px solid red'); }, emailInputError: function() { $inloginPopupTypeSirikhu.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, emailInputNotFoundError: function() { $inloginPopupTypeSirikhu.validateLogin().emailError(); $("#login-error-email").addClass("error"); $("#login-error-email").css('opacity', 1).html('ไม่พบอีเมลนี้ในข้อมูลสมาชิก Email is not found'); }, emailInputNullError: function() { $inloginPopupTypeSirikhu.validateLogin().emailError(); $("#login-error-email").addClass("error"); // $("#login-error-email").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#login-password-v1').val(); if (v.length <= 0) { $inloginPopupTypeSirikhu.validateLogin().passwordInputNullError(); $inloginPopupTypeSirikhu.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inloginPopupTypeSirikhu.error_password = false; /*$inloginPopupTypeSirikhu.validateLogin().passwordOk();*/ return true; } else if (v.length > 0 && v.length < 6) { $inloginPopupTypeSirikhu.error_password = true; $inloginPopupTypeSirikhu.shake(); $inloginPopupTypeSirikhu.validateLogin().passwordInputError(); return false; } }, passwordOk: function() { $("#login-password-v1").css('border', '2px solid green'); $inloginPopupTypeSirikhu.validateLogin().passwordInputOk(); }, passwordInputOk: function() { $("#login-error-password").removeClass("error"); $("#login-error-password").css('opacity', 0); }, passwordError: function() { $("#login-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inloginPopupTypeSirikhu.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputPasswordWrongError: function() { $inloginPopupTypeSirikhu.validateLogin().passwordError(); $("#login-error-password").addClass("error"); $("#login-error-password").css('opacity', 1).html('รหัสไม่ถูกต้อง Password is wrong'); }, passwordInputNullError: function() { $inloginPopupTypeSirikhu.validateLogin().passwordError(); $("#login-error-password").addClass("error"); // $("#login-error-password").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetEmail: function() { $("#login-email-v1").css('border', ''); $("#login-email-v1").val(''); $("#login-error-email").css('opacity', 0); }, resetPassword: function() { $("#login-password-v1").css('border', ''); $("#login-password-v1").val(''); $("#login-error-password").css('opacity', 0); }, reset: function() { $inloginPopupTypeSirikhu.validateLogin().resetEmail(); $inloginPopupTypeSirikhu.validateLogin().resetPassword(); }, }; return promise; }; /* validateLogin */ /* load html */ $inloginPopupTypeSirikhu.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inloginPopupTypeSirikhu.whenOnLoad = function(shopId) {}; $inloginPopupTypeSirikhu.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.login_vSirikhu_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.login_vSirikhu_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, }; /* load html */ /* submitLogin */ $inloginPopupTypeSirikhu.submitLogin = function() { $inloginPopupTypeSirikhu.login.email = $('#login-email-v1').val(); $inloginPopupTypeSirikhu.login.password = $('#login-password-v1').val(); var userEmail = $inloginPopupTypeSirikhu.login.email; var userPass = $inloginPopupTypeSirikhu.login.password; var userEmailValid = $inloginPopupTypeSirikhu.validateLogin().email(); var userPassValid = $inloginPopupTypeSirikhu.validateLogin().password(); console.log("submitLogin", "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); if (!userEmailValid || !userPassValid) { console.log("submitLogin", "return"); $inloginPopupTypeSirikhu.shake(); return; } $inloginPopupTypeSirikhu.validateLogin().checkEmail(userEmail, function(resultCheck) { console.log("submitLogin", resultCheck); if (resultCheck.ok == 1) { console.log('submitLogin true'); $inloginPopupTypeSirikhu.validateLogin().emailInputNotFoundError(); $inloginPopupTypeSirikhu.validateLogin().passwordInputPasswordWrongError(); $inloginPopupTypeSirikhu.error.email = true; $inloginPopupTypeSirikhu.error.emailExist = true; } else { console.log('submitLogin false'); return $inloginPopupTypeSirikhu.sendSubmitLogin(false); } }); }; /* submitLogin */ /* sendSubmitLogin */ $inloginPopupTypeSirikhu.sendSubmitLogin = function(reCheck) { $inloginPopupTypeSirikhu.login.pressing = true; var userEmail = $inloginPopupTypeSirikhu.login.email; var userPass = $inloginPopupTypeSirikhu.login.password; $inloginPopupTypeSirikhu.login.remember = $('#login-remember-v1')[0].checked; var userRemember = $inloginPopupTypeSirikhu.login.remember; console.log("sendSubmitLogin : userRemember : ", userRemember); if (reCheck) { /* if error : user */ if (userEmail.length <= 0) { $inloginPopupTypeSirikhu.validateLogin().emailInputError(); } else { $inloginPopupTypeSirikhu.validateLogin().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $inloginPopupTypeSirikhu.validateLogin().passwordOk(); } else { $inloginPopupTypeSirikhu.validateLogin().passwordInputError(); } /* email */ if (userEmail.length > 0 && !$inloginPopupTypeSirikhu.helper.isEmail(userEmail)) { $inloginPopupTypeSirikhu.error_email = true; } else { $inloginPopupTypeSirikhu.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inloginPopupTypeSirikhu.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inloginPopupTypeSirikhu.error_password = true; } if ($inloginPopupTypeSirikhu.error_password || $inloginPopupTypeSirikhu.error_email) { return; } } /* loading */ $inloginPopupTypeSirikhu.helper.pageLoad(); var token_login = {}; var hash_password = {}; var dataSendOne = { 'txt_email': userEmail }; var saveStorageData = {}; console.log("sendSubmitLogin : dataSendOne : ", dataSendOne); GAEAPI.post('customer/token_login', dataSendOne).then(function(e) { console.log("sendSubmitLogin : e : ", e); token_login = e.data; var dataSendTwo = { 'txt_password': userPass, 'txt_key_token': token_login.key_token, 'txt_secret_token': token_login.secret_token, }; GAEAPI.post('customer/generate_hash_password', dataSendTwo).then(function(ee) { hash_password = ee.data; var dataSendThree = { 'txt_email': userEmail, 'txt_hash_password': hash_password.hash_password }; saveStorageData.data_three = dataSendThree; GAEAPI.post('customer/login', dataSendThree).then(function(eee) { /* console.log("customer/login : done : ", eee); */ if (eee.ok == 1) { var data = GAEAPI.getValue(eee.data); var cookie_key = "gae_access_token_shop_" + GAEAPI.getHeaderForKey('base_shop_id') + "_customer"; var gae_access_token = GAEAPI.getValueForKey(data, cookie_key, ""); saveStorageData.gae_access_token = gae_access_token; if (userRemember) { /*console.log("login : setting cookie");*/ GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 24 * 360)); setTimeout(function() { $inloginPopupTypeSirikhu.helper.pageUnLoad(); $inloginPopupTypeSirikhu.close(); location.reload(); }, 100); } else { /* console.log("PressLogin -:- CookieLoginDestroy : "); */ console.log("PressLogin -:- CookieLoginDestroy : eee : ", eee); GAEAPI.setUserData(cookie_key, gae_access_token, (60 * 60 * 3)); setTimeout(function() { $inloginPopupTypeSirikhu.helper.pageUnLoad(); $inloginPopupTypeSirikhu.close(); location.reload(); }, 100); $inloginPopupTypeSirikhu.getMe = eee.data; console.log("PressLogin -:- CookieLoginDestroy : getMe : ", $inloginPopupTypeSirikhu.getMe); UiCustomerBox.apiGetCustomerData(function() {}); location.reload(); /* location.reload(); */ /* RELOAD URL() */ } } else { $inloginPopupTypeSirikhu.helper.pageUnLoad(); setTimeout(function() { $inloginPopupTypeSirikhu.validateLogin().passwordInputError(); $inloginPopupTypeSirikhu.error.password = true; $inloginPopupTypeSirikhu.error.wrong_password = true; }, 500); } }); }); }); /* loading */ }; /* sendSubmitLogin */ /* viewPassword */ $inloginPopupTypeSirikhu.viewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); if (t === 'password') { e.setAttribute('type', 'text'); } else { e.setAttribute('type', 'password'); } return true; }; $inloginPopupTypeSirikhu.resetViewPassword = function(elementId) { var e = document.getElementById(elementId); var t = e.getAttribute('type'); e.setAttribute('type', 'password'); return true; }; /* viewPassword */ $inloginPopupTypeSirikhu.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* loginSocialShow */ $inloginPopupTypeSirikhu.loginSocialShow = function() { /* $inloginPopupTypeSirikhu.login.facebook = face; $inloginPopupTypeSirikhu.login.twitter = twit; $inloginPopupTypeSirikhu.login.google = google; */ if (!$inloginPopupTypeSirikhu.login.facebook) { $('.form_large .facebook').css('display', 'none'); } else {} if (!$inloginPopupTypeSirikhu.login.twitter) { $('.form_large .twitter').css('display', 'none'); } else {} if (!$inloginPopupTypeSirikhu.login.google) { $('.form_large .google').css('display', 'none'); } else {} } /* Open */ var timerAdjustOpen = 0; $inloginPopupTypeSirikhu.isOpen = false; $inloginPopupTypeSirikhu.open = function() { $inloginPopupTypeSirikhu.loginSocialShow(); $inloginPopupTypeSirikhu.resetViewPassword('login-password-v1'); $inloginPopupTypeSirikhu.validateLogin().reset(); $(".login_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden', }); $('body').css({ 'overflow': 'auto', 'position': 'unset' }); timerAdjustOpen = setTimeout(function() { $(".login.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inloginPopupTypeSirikhu.submitLogin(); } }); }; /* Open */ /* Close */ $inloginPopupTypeSirikhu.close = function() { $(".login_overlay").removeClass("is_open"); $(".login.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inloginPopupTypeSirikhu.shake = function() { $(".login.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".login.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* register */ $inloginPopupTypeSirikhu.register = function() { $inloginPopupTypeSirikhu.close(); $inregisterPopupTypeSirikhu.open(); } /* register */ /* register */ $inloginPopupTypeSirikhu.forgotpassword = function() { $inloginPopupTypeSirikhu.close(); $inforgotpasswordPopupTypeSirikhu.open(); } /* register */ /* LoginFacebook */ $inloginPopupTypeSirikhu.loginFacebook = function() { /*console.log("loginFacebook : loginFacebook ");*/ FB.getLoginStatus(function(response) { $inloginPopupTypeSirikhu.statusChangeCallback(response); }); } $inloginPopupTypeSirikhu.statusChangeCallback = function(response) { /*console.log("statusChangeCallback : ", response);*/ if (response.status === 'connected') { /*console.log("statusChangeCallback : if ", response);*/ } else { /*console.log("statusChangeCallback : else ", response);*/ } FB.login(function(response) { if (response.authResponse) { console.log("statusChangeCallback response.authResponse : ", response.authResponse); FB.api('/me?fields=email,birthday,location,locale,age_range,currency,first_name,last_name,name_format,gender&access_token=', function(response) { /*console.log('statusChangeCallback JSON : , ', JSON.stringify(response));*/ }); var accessToken = response.authResponse.accessToken; var user_id = response.authResponse.userID; var dataSend = { txt_fb_access_token: accessToken, }; /*console.log("statusChangeCallback : dataSend : ", dataSend);*/ UiCustomerBox.api.post("customer/facebook_login", dataSend).then(function(res) { /*console.log("customer/facebook_login : res", res);*/ if (res.ok == 1) { UiCustomerBox.callEventScript("on.justLogin", res.data); setTimeout(function() { $inloginPopupTypeSirikhu.helper.pageUnLoad(); $inloginPopupTypeSirikhu.close(); }, 100); UiCustomerBox.apiGetCustomerData(function() {}); /*location.reload();*/ /* RELOAD URL() */ } else { error.log('statusChangeCallback error.'); } }); } else { /*console.log('User cancelled login or did not fully authorize.');*/ } }, { scope: "email" }) } /* LoginFacebook */ /* Init */ /* Init */ /* Init */ $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { /* normal design */ case 544: $inloginPopupTypeSirikhu.install(currentShopId, true); $inloginPopupTypeSirikhu.installFacebook("553027035120781", "https://sirikhun.com/"); $inregisterPopupTypeSirikhu.install(currentShopId, false); $inforgotpasswordPopupTypeSirikhu.install(currentShopId, false); break; default: break; } });_ui_share_app.directive('componentMenuFacSlide', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentMenuFacSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', position: '@position', textstyle: '@textstyle', buttonstyle: '@buttonstyle', animatestyle: '@animatestyle', margin: '@margin', font: '@font', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.ref_id = $routeParams.referral_id; $scope.relate_name = $routeParams.referral_relate_name; $scope.type = 'BrandSlide'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; if (!carouselData.get($scope.type) && !$scope.data.length) { var dataSend = { 'txt_referral_type_id': 17, 'cur_page': 1, 'per_page': 100, }; GAEAPI.get('referral/lists', dataSend, $scope).then(function(res) { if (res.ok != 1) { return; } var resultArray = res.data.dataList; if (resultArray.length) { carouselData.set($scope.type, resultArray); console.log("datatest1232", resultArray); $scope.data = resultArray; } else { $scope.done = true; return; } var t = $interval(function() { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function() { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); }); } else { $scope.data = carouselData.get($scope.type); console.log("%ccarouselData => get state", "background-color:yellow;color:black;padding:5px;"); var t = $interval(function() { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function() { $timeout.cancel(tt); $scope.initSlider(); }, 300); } }, 500); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 6, slidesToScroll: 1, dots: false, arrows: true, infinite: true, responsive: [{ breakpoint: 991, settings: { arrows: false, slidesToShow: 4 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 2 } }] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { var a = i; if (a.indexOf('http') == -1) { return 'http://' + i; } return i; }; $scope.slickGoLeft = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.component_carousel_map[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.checkChild = function(object) { return (!object.referral_sub_array.length) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; }); _ui_share_app.directive('componentPadding', function ($rootScope, $routeParams) { var templateName = 'componentPadding'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', }; promise.link = function (scope, element, attr) {}; promise.template = '
'; promise.transclude = false; return promise; }); _ui_share_app.factory('$componentPageContact', function componentPageContact($routeParams, $timeout) { return });_ui_share_app.directive('componentPageContactBoxcontact', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'boxcontact'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { img1: '@img1', img2: '@img2', img3: '@img3', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.icnPath = 'extensions/themes/assets/'; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; $scope.buildIframeMapByLoc(e.data.shop_gps_array[0].name, e.data.shop_gps_array[0].lat, e.data.shop_gps_array[0].lng); } }); }; $scope.getShopCurrent(); $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.urlGoogle = ''; $scope.jsonGoogle = []; $scope.buildIframeMapByLoc = function(name, lat, lng) { console.log("componentPageContactShowmap", name, lat, lng); var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var path = GURL.base_url() + 'extensions/devsource/dev.sugarfree/dealer/placeApi.php?name=' + name; var key = 'AIzaSyAnRlEEOQv7EiSMECtrHk0MkLizJNRYRIo'; $scope.urlGoogle = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=' + newName + '&key=' + key; var placeOK = function() { $scope.urlgooglemap = 'https://www.google.com/maps/embed/v1/place?q=' + newName + '&key=AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18'; $scope.url_search = 'https://www.google.com/maps/search/?api=1&query='+newName+'+field'; }; var placeNo = function() { $scope.urlgooglemap = 'https://www.google.com/maps/embed/v1/place?q=' + lat + ',' + lng + '&key=AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18'; $scope.url_search = 'https://www.google.com/maps/search/?api=1&query='+lat+','+lng; // https://www.google.com/maps/search/?api=1&query=47.5951518,-122.3316393&query_place_id=ChIJKxjxuaNqkFQR3CK6O1HNNqY }; $.getJSON(path, function(json) { $scope.jsonGoogle = json; console.log("jsonGoogle", json); if (json.google_result.status === "OK") { placeOK(); } else { placeNo(); } }); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactA', function($rootScope, $routeParams) { var templateName = 'componentPageContactA'; var componentMain = 'componentPageContact'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact_: '@contact', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'form_map_iframe': '?formMapIframe', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopCurrent = e.data; $scope.shopname = $scope.shopCurrent.shop_name; } }); }; $scope.getShopCurrent(); $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactB', function($rootScope, $routeParams) { var templateName = 'componentPageContactB'; var componentMain = 'componentPageContact'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact_: '@contact', texttop:'@texttop', name: '@name', backgroundcolor: '@backgroundcolor', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'contact_top': '?contactTop', 'contact_left': '?contactLeft', 'contact_right': '?contactRight', 'form_map_iframe': '?formMapIframe', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.shopCurrent = []; $scope.language = ''; $scope.currentShopId = parseInt(CUR_THEME.shop_id()); $scope.shopIdlanguage = function() { switch ($scope.currentShopId) { case 646: /* TH */ $scope.language = 'th'; break; case 713: /* TH */ $scope.language = 'th'; break; case 718: /* TH */ $scope.language = 'th'; break; default: /* EN */ $scope.language = 'en'; break; } } $scope.shopIdlanguage(); $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopCurrent = e.data; $scope.shopname = $scope.shopCurrent.shop_name; } }); }; $scope.getShopCurrent(); $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactC', function($rootScope, $routeParams) { var templateName = 'componentPageContactC'; var componentMain = 'componentPageContact'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact_: '@contact', socielshow: '@socielshow' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'contact_us': '?contactUs', 'form_map_iframe': '?formMapIframe', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopCurrent = e.data; $scope.shopname = $scope.shopCurrent.shop_name; } }); }; $scope.getShopCurrent(); $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactD', function($rootScope, $routeParams) { var templateName = 'componentPageContactD'; var componentMain = 'componentPageContact'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact_: '@contact', name:'@name', mapheight:'@mapheight', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'contact_top': '?contactTop', 'contact_left': '?contactLeft', 'contact_right': '?contactRight', 'form_map_iframe': '?formMapIframe', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopCurrent = e.data; $scope.shopname = $scope.shopCurrent.shop_name; } }); }; $scope.getShopCurrent(); $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactE', function($rootScope, $routeParams) { var templateName = 'componentPageContactE'; var componentMain = 'componentPageContact'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact_: '@contact', name:'@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'contact_top': '?contactTop', 'contact_left': '?contactLeft', 'contact_right': '?contactRight', 'form_map_iframe': '?formMapIframe', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._param = $routeParams.menu; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopCurrent = e.data; $scope.shopname = $scope.shopCurrent.shop_name; } }); }; $scope.getShopCurrent(); $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontact', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontact'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact: '@contact', name: '@name', stylebutton: '@stylebutton', stylefontcolor: '@stylefontcolor', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round'; $scope._stylefontcolor = (typeof $scope.stylefontcolor !== 'undefined' && typeof $scope.stylefontcolor !== '') ? $scope.stylefontcolor : 'primary_text'; $scope.language = ''; $scope.currentShopId = parseInt(CUR_THEME.shop_id()); $scope.shopIdlanguage = function() { switch ($scope.currentShopId) { case 541: /* TH */ $scope.language = 'th'; break; case 645: /* TH */ $scope.language = 'th'; break; case 646: /* TH */ $scope.language = 'th'; break; case 713: /* TH */ $scope.language = 'th'; break; case 718: /* TH */ $scope.language = 'th'; break; case 801: /* TH */ $scope.language = 'th'; break; default: /* EN */ $scope.language = 'en'; break; } } $scope.shopIdlanguage(); $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; /* Watch Value */ $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else {} if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_contact', $scope.contact_email); formData.append('input_owner_name', $scope.shopname); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactB', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactB'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact: '@contact', nature: '@nature', textbutton: '@textbutton', stylebutton: '@stylebutton', datafont : '@datafont' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.textbutton = (typeof $scope.textbutton !== 'undefined') ? $scope.textbutton : 'Send'; $scope.stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_small'; $scope.databtnfont = (typeof $scope.datafont !== 'undefined') ? $scope.datafont : ''; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_name_valid = false; $scope.input_email_valid = false; $scope.input_number_valid = false; $scope.input_topic_valid = false; $scope.input_message_valid = false; /* Watch Value */ $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_number', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_number_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_number_valid = true; } else { $scope.input_number_valid = false; } }); $scope.$watch('input_topic', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_topic_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_topic_valid = true; } else { $scope.input_topic_valid = false; } }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_nature', $scope.nature); formData.append('input_owner_contact', $scope.contact_email); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_topic = ""; $scope.input_topic_valid = false; $scope.input_message = ""; $scope.input_message_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_topic = ""; $scope.input_topic_valid = false; $scope.input_message = ""; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactBs', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactBs'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact: '@contact', nature: '@nature', textbutton: '@textbutton', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.textbutton = (typeof $scope.textbutton !== 'undefined') ? $scope.textbutton : 'Send'; $scope.stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_small'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; /* Form Validate */ $scope.input_name_valid = false; $scope.input_email_valid = false; $scope.input_number_valid = false; $scope.input_topic_valid = false; $scope.input_cook_valid = false; $scope.input_useoil_valid = false; $scope.input_address_valid = false; /* Watch Value */ $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_number', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_number_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_number_valid = true; } else { $scope.input_number_valid = false; } }); $scope.$watch('input_topic', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_topic_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_topic_valid = true; } else { $scope.input_topic_valid = false; } }); $scope.$watch('input_address', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_address_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_address_valid = true; } else { $scope.input_address_valid = false; } }); $scope.$watch('input_cook', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_cook_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_cook_valid = true; } else { $scope.input_cook_valid = false; } }); $scope.$watch('input_useoil', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_useoil_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_useoil_valid = true; } else { $scope.input_useoil_valid = false; } }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_nature', $scope.nature); formData.append('input_owner_contact', $scope.contact_email); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email-shop-contact.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_topic = ""; $scope.input_topic_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_topic = ""; $scope.input_topic_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactC', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactC'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact: '@contact', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_small'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_name_valid = false; $scope.input_salary_valid = false; $scope.input_email_valid = false; $scope.input_daystart_valid = false; $scope.input_number_valid = false; $scope.input_public_figure_valid = false; /* Watch Value */ $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_number', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_number_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_number_valid = true; } else { $scope.input_number_valid = false; } }); $scope.$watch('input_topic', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_topic_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_topic_valid = true; } else { $scope.input_topic_valid = false; } }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { alert("กรุณากรอกอีเมลของท่านให้ถูกต้อง"); } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_contact', $scope.contact_email); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_salary = ""; $scope.input_salary_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_daystart = ""; $scope.input_daystart_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_public_figure = ""; $scope.input_public_figure_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_salary = ""; $scope.input_salary_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_daystart = ""; $scope.input_daystart_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_public_figure = ""; $scope.input_public_figure_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactD', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactD'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact: '@contact', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_name_valid = false; $scope.input_salary_valid = false; $scope.input_email_valid = false; $scope.input_daystart_valid = false; $scope.input_number_valid = false; $scope.input_public_figure_valid = false; /* Watch Value */ $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_number', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_number_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_number_valid = true; } else { $scope.input_number_valid = false; } }); $scope.$watch('input_location_open', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_business_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_business_valid = true; } else { $scope.input_business_valid = false; } }); $scope.$watch('input_budget', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_budget_valid = false; return; } $scope.input_budget_valid = true; }); $scope.$watch('input_business', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_business_valid = false; return; } $scope.input_business_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { alert("กรุณากรอกอีเมลของท่านให้ถูกต้อง"); } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_contact', $scope.contact_email); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_salary = ""; $scope.input_salary_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_daystart = ""; $scope.input_daystart_valid= false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_public_figure = ""; $scope.input_public_figure_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_salary = ""; $scope.input_salary_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_daystart = ""; $scope.input_daystart_valid= false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_public_figure = ""; $scope.input_public_figure_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactE', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactE'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact: '@contact', nature: '@nature', textbutton: '@textbutton', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.textbutton = (typeof $scope.textbutton !== 'undefined') ? $scope.textbutton : 'Send'; $scope.stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_small'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_name_valid = false; $scope.input_email_valid = false; $scope.input_number_valid = false; $scope.input_topic_valid = false; $scope.input_message_valid = false; /* Watch Value */ $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_number', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_number_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_number_valid = true; } else { $scope.input_number_valid = false; } }); $scope.$watch('input_topic', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_topic_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_topic_valid = true; } else { $scope.input_topic_valid = false; } }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { // alert("กรุณากรอกอีเมลของท่านให้ถูกต้อง"); } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_nature', $scope.nature); formData.append('input_owner_contact', $scope.contact_email); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_topic = ""; $scope.input_topic_valid = false; $scope.input_message = ""; $scope.input_message_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_topic = ""; $scope.input_topic_valid = false; $scope.input_message = ""; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactF', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactF'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { email: '@email', contact: '@contact', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_small'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = (typeof $scope.email !== 'undefined' && $scope.email !== '') ? $scope.email : e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_name_valid = false; $scope.input_salary_valid = false; $scope.input_email_valid = false; $scope.input_daystart_valid = false; $scope.input_number_valid = false; $scope.input_public_figure_valid = false; $scope.input_job_position_valid = false /* Watch Value */ $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_number', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_number_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_number_valid = true; } else { $scope.input_number_valid = false; } }); $scope.$watch('input_topic', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_topic_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_topic_valid = true; } else { $scope.input_topic_valid = false; } }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { // alert("กรุณากรอกอีเมลของท่านให้ถูกต้อง"); } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_contact', $scope.contact_email); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_salary = ""; $scope.input_salary_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_daystart = ""; $scope.input_daystart_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_public_figure = ""; $scope.input_public_figure_valid = false; $scope.input_message = ""; $scope.input_message_valid = false; $scope.input_job_position = ""; $scope.input_job_position_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_salary = ""; $scope.input_salary_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_daystart = ""; $scope.input_daystart_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_public_figure = ""; $scope.input_public_figure_valid = false; $scope.input_job_position = ""; $scope.input_job_position_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactG', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactG'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact: '@contact', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_small'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.data = { input_name: "", input_nickname: "", input_gender: "", input_addrees: "", input_number: "", input_email: "", input_date_birth: "", input_contact_details: "", input_contact_details_number: "", input_medical: "", input_medication: "" } $scope.input = { input_name: false, input_nickname: false, input_gender: false, input_addrees: false, input_number: false, input_email: false, input_date_birth: false, input_contact_details: false, input_contact_details_number: false, input_medical: false, input_medication: false } /* Watch Value */ $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input.input_email = false; return; } if ($scope.isEmail(newValue)) { $scope.input.input_email = true; $("[name='input_email']").removeClass('error'); } else { $scope.input.input_email = false; $("[name='input_email']").addClass('error'); } }); $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input.input_name = false; return; } $scope.input.input_name = true; }); $scope.$watch('input_nickname', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input.input_nickname = false; return; } $scope.input.input_nickname = true; }); $scope.$watch('input_gender', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input.input_gender = false; return; } $scope.input.input_gender = true; }); $scope.$watch('input_addrees', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input.input_addrees = false; return; } $scope.input.input_addrees = true; }); $scope.$watch('input_date_birth', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input.input_date_birth = false; return; } $scope.input.input_date_birth = true; }); $scope.$watch('input_contact_details', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input.input_contact_details = false; return; } $scope.input.input_contact_details = true; }); $scope.$watch('input_contact_details_number', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input.input_contact_details_number = false; return; } if ($scope.telephoneCheck(newValue)) { $scope.input.input_contact_details_number = true; $("[name='input_contact_details_number']").removeClass('error'); } else { $scope.input.input_contact_details_number = false; $("[name='input_contact_details_number']").addClass('error'); } }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; $("[name='input_email']").removeClass('error'); } else { $("[name='input_email']").addClass('error'); } var isPassNumber = false; if ($scope.telephoneCheck($('#contact_form input[name="input_number"]').val())) { isPassNumber = true; $("[name='input_number']").removeClass('error'); } else { $("[name='input_number']").addClass('error'); } console.log("isPassNumber : ", isPassNumber); var isPassContactDetailsNumber = false; if ($scope.telephoneCheck($('#contact_form input[name="input_contact_details_number"]').val())) { isPassContactDetailsNumber = true; $("[name='input_contact_details_number']").removeClass('error'); } else { $("[name='input_contact_details_number']").addClass('error'); } console.log("isPassContactDetailsNumber : ", isPassContactDetailsNumber); if ($scope.contact !== "" && submit && isPass && isPassNumber && isPassContactDetailsNumber) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); $('html, body').animate({ scrollTop: $(".contact_success").offset().top - 230 }, 100); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_contact', $scope.contact_email); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-intake-form.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_salary = ""; $scope.input_salary_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_daystart = ""; $scope.input_daystart_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.input_public_figure = ""; $scope.input_public_figure_valid = false; $scope.input_job_position = ""; $scope.input_job_position_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.telephoneCheck = function(inputString) { var re = /^(([0-9]{3}))([0-9]{3})([0-9]{4})$/; return re.test(inputString); } $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactH', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactH'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { contact: '@contact', name: '@name', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round'; $scope.language = ''; $scope.currentShopId = parseInt(CUR_THEME.shop_id()); $scope.shopIdlanguage = function() { switch ($scope.currentShopId) { case 541: /* TH */ $scope.language = 'th'; break; case 645: /* TH */ $scope.language = 'th'; break; case 646: /* TH */ $scope.language = 'th'; break; case 713: /* TH */ $scope.language = 'th'; break; case 718: /* TH */ $scope.language = 'th'; break; default: /* EN */ $scope.language = 'en'; break; } } $scope.shopIdlanguage(); $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; /* Watch Value */ $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else {} if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } var isPassNumber = false; if ($scope.telephoneCheck($('#contact_form input[name="input_number"]').val())) { isPassNumber = true; $("[name='input_number']").removeClass('error'); } else { $("[name='input_number']").addClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass && isPassNumber) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_contact', $scope.contact_email); formData.append('input_owner_name', $scope.shopname); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.telephoneCheck = function(inputString) { var re = /^(([0-9]{3}))([0-9]{3})([0-9]{4})$/; return re.test(inputString); } $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactJobA', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactJobA'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { email: '@email', contact: '@contact', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_small'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { /* console.log('componentPageContactFromcontactJobA : ', name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.setData = [{ api: "shop/current", dataSend: [], dataArray: [], dataArrayState: { load: false, done: false } }]; $scope.inputData = { input_name: "", input_email: "", input_number: "", input_salary: "", input_daystart: "", input_job_position: "", input_job_position_e: "", input_educational: "", input_graduated: "", input_faculty_branch: "", input_gpa: "", input_message: "", input_picture: "" }; $scope.getData().getRouteParams(function(params) { $scope.setData[0].dataArrayState = $scope.getData().stateData(true, false); $scope.getData().dataSend($scope.setData[0].api, $scope.setData[0].dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.setData[0].dataArray = output; $scope.setData[0].dataArrayState = $scope.getData().stateData(false, true); if ($scope.email != undefined || $scope.email != '') { $scope.setData[0].dataArray.data.shop_extend_data.contact_email = $scope.email; } }); }); }); $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.dataArrayState = { states: true, email: false, load: false, done: false }; $scope.$watch('inputData.input_job_position', function(newValue, oldValue) { if ($scope.inputData.input_job_position != 'อื่นๆ(โปรดระบุ)') { $scope.inputData.input_job_position_e = $scope.inputData.input_job_position; } else { $scope.inputData.input_job_position_e = ""; } }); $scope.submit = function($event) { $scope.dataArrayState.states = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); $scope.dataArrayState.states = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { $("[name='input_email']").removeClass('error'); $scope.dataArrayState.email = true; } else { $("[name='input_email']").addClass('error'); $scope.dataArrayState.email = false; } if ($scope.setData[0].dataArrayState.done && $scope.dataArrayState.states && $scope.dataArrayState.email) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.setData[0].dataArray.data.shop_name); formData.append('input_owner_contact', $scope.setData[0].dataArray.data.shop_extend_data.contact_email); $scope.getData().consoleLog("submit : formData : ", formData); $.ajax({ url: _ui_share_host + '../sendgrid/postprecast-send-email-job.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); } }); } else {} }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactPreOrderA', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactPreOrderA'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', fontstyle: '@fontstyle', btnstyle: '@btnstyle', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = "componentPageContactFromcontactPreOrderA"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._fontstyle = ($scope.fontstyle != undefined && $scope.fontstyle != "") ? $scope.fontstyle : "primary_text"; $scope._btnstyle = ($scope.btnstyle != undefined && $scope.btnstyle != "") ? $scope.btnstyle : "filled_button_large"; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { console.log($scope._component, ' : ', functionName, ' : ', data); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, main: function() { var _self = this; } } return getFunction; }; $scope.formArray = [{ form_title: "สินค้าที่ต้องการสั่งซื้อ", form_error: "กรุณากรอกสินค้าที่ต้องการสั่งซื้อ ของท่าน", type: { name: "input_product", type: [{ type: "input" }, { type: "text" }], data: "" } }, { form_title: "ชื่อ-สกุล", form_error: "กรุณากรอกชื่อ-สกุล ของท่าน", type: { name: "input_name", type: [{ type: "input" }, { type: "text" }], data: "" } }, { form_title: "ที่อยู่", form_error: "กรุณากรอกที่อยู่ ของท่าน", type: { name: "textarea_address", type: [{ type: "textarea" }, { type: "text" }], data: "" } }, { form_title: "อีเมล", form_error: "กรุณากรอกอีเมล ของท่าน", type: { name: "input_email", type: [{ type: "input" }, { type: "text" }], data: "" } }, { form_title: "เบอร์โทรติดต่อ", form_error: "กรุณากรอกเบอร์โทรติดต่อ ของท่าน", type: { name: "input_phone", type: [{ type: "input" }, { type: "text" }], data: "" } }, { form_title: "ส่งคำสั่งซื้อ", form_error: "", type: { name: "button_send", type: [{ type: "button" }, { type: "text" }], data: "" } }]; /* shop */ $scope.setData = { dataSend: {}, api: "shop/current", ok: false, dataArray: [], dataArrayState: { load: false, done: false }, submitState: { load: false, done: false } }; /* shop */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.setData.dataArrayState = res_state; $scope.getData().dataSend($scope.setData.api, $scope.setData.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api, res_state) { $scope.setData.ok = res_ok; $scope.setData.dataArray = get_res_api.data; $scope.setData.dataArrayState = res_state; }); }); }); $scope.format = function() { var getFunction = { isEmail: function(email, callback) { var state = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var res_state = state.test(email); callback(res_state); }, isPhone: function(email, callback) { var state = /^(([0-9]{3}))([0-9]{3})([0-9]{4})$/; var res_state = state.test(email); callback(res_state); } } return getFunction; }; $scope.formSubmit = function($event) { $scope.setData.submitState = $scope.getData().stateData(true, false); $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); $scope.setData.submitState = $scope.getData().stateData(false, false); } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var email = $('#contact_form_pre_order input[name="input_email"]').val(); $scope.format().isEmail(email, function(res_state) { if (res_state) { $("[name='input_email']").removeClass('error'); } else { $scope.setData.submitState = $scope.getData().stateData(false, false); $("[name='input_email']").addClass('error'); } }); var phone = $('#contact_form_pre_order input[name="input_phone"]').val(); $scope.format().isPhone(phone, function(res_state) { if (res_state) { $("[name='input_phone']").removeClass('error'); } else { $scope.setData.submitState = $scope.getData().stateData(false, false); $("[name='input_phone']").addClass('error'); } }); if ($scope.setData.submitState.load && !$scope.setData.submitState.done) { var formData = new FormData($('#contact_form_pre_order')[0]); formData.append('input_owner_name', $scope.setData.dataArray.shop_name); if ($scope.setData.dataArray.shop_extend_data.contact_email != '') { formData.append('input_owner_contact', $scope.setData.dataArray.shop_extend_data.contact_email); $scope.getData().consoleLog("formSubmit : formData : ", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email-pre-order-a.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { $scope.setData.submitState = $scope.getData().stateData(false, true); }, 2000); }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { $scope.setData.submitState = $scope.getData().stateData(false, false); }, 2000); } }); } else { $scope.setData.submitState = $scope.getData().stateData(false, false); } } }; }; return promise; });_ui_share_app.directive('componentPageContactFromcontactQuotationA', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'fromcontactQuotationA'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { email: '@email', contact: '@contact', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_small'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { /* console.log('componentPageContactFromcontactJobA : ', name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.setData = [{ api: "shop/current", dataSend: [], dataArray: [], dataArrayState: { load: false, done: false } }]; $scope.inputData = { input_name: "", input_email: "", input_address: "", input_number: "", input_message: "", input_picture: "" }; $scope.getData().getRouteParams(function(params) { $scope.setData[0].dataArrayState = $scope.getData().stateData(true, false); $scope.getData().dataSend($scope.setData[0].api, $scope.setData[0].dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.setData[0].dataArray = output; $scope.setData[0].dataArrayState = $scope.getData().stateData(false, true); }); }); }); $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.dataArrayState = { states: true, email: false, load: false, done: false }; $scope.submit = function($event) { $scope.dataArrayState.states = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); $scope.dataArrayState.states = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { $("[name='input_email']").removeClass('error'); $scope.dataArrayState.email = true; } else { $("[name='input_email']").addClass('error'); $scope.dataArrayState.email = false; } if ($scope.setData[0].dataArrayState.done && $scope.dataArrayState.states && $scope.dataArrayState.email) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.setData[0].dataArray.data.shop_name); formData.append('input_owner_contact', $scope.setData[0].dataArray.data.shop_extend_data.contact_email); $scope.getData().consoleLog("submit : formData : ", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email-quotation-a.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); } }); } else {} }; }; return promise; });_ui_share_app.directive('componentPageContactShowcontact', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'showcontact'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; } }); }; $scope.getShopCurrent(); $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactShowcontactB', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'showcontactB'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; } }); }; $scope.getShopCurrent(); $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactShowmap', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'showmap'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.urlgooglemap = ''; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; $scope.buildIframeMapByLoc(e.data.shop_gps_array[0].name, e.data.shop_gps_array[0].lat, e.data.shop_gps_array[0].lng); } }); }; $scope.getShopCurrent(); $scope.urlGoogle = ''; $scope.jsonGoogle = []; $scope.buildIframeMapByLoc = function(name, lat, lng) { console.log("componentPageContactShowmap", name, lat, lng); var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var path = GURL.base_url() + 'extensions/devsource/dev.sugarfree/dealer/placeApi.php?name=' + name; var key = 'AIzaSyAnRlEEOQv7EiSMECtrHk0MkLizJNRYRIo'; $scope.urlGoogle = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=' + newName + '&key=' + key; var placeOK = function() { $scope.urlgooglemap = 'https://www.google.com/maps/embed/v1/place?q=' + newName + '&key=AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18'; }; var placeNo = function() { if (lat != 0 || lng != 0) { $scope.urlgooglemap = 'https://www.google.com/maps/embed/v1/place?q=' + lat + ',' + lng + '&key=AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18'; } }; $.getJSON(path, function(json) { $scope.jsonGoogle = json; console.log("jsonGoogle", json); if (json.google_result.status === "OK") { placeOK(); } else { placeNo(); } }); }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPageContactShowopendaytime', function($rootScope, $routeParams) { var componentMain = 'componentPageContact'; var componentChild = 'showopendaytime'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._day = ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัสบดี", "ศุกร์", "เสาร์"]; $scope.data = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; } }); console.log("shop_open_daytime : ", $scope.data.shop_open_daytime); }; $scope.getShopCurrent(); $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });/*_ui_share_app.directive('componentFooter', function($rootScope, $routeParams) { var templateName = 'componentFooter'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id: '=', background: '@', primary: '@', secondary: '@', name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) {}; return promise; });*/ _ui_share_app.factory('$componentPages', function componentPages($routeParams, $timeout) { return });_ui_share_app.directive('componentPagesListsA', function($rootScope, $routeParams) { var templateName = 'componentPagesListsA'; var componentMain = 'componentPages'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarousel = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 3 } }, { breakpoint: 768, settings: { slidesToShow: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._dataArray = []; $scope.data_last_array = false; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { 'badge_id_array': [18] } var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('page/lists', dataSend).then(function(res) { if (res.ok === 1) { if(CUR_THEME.shop_id() == 635){ // $scope._dataArray = res.data.dataList; for (var i = 0; i < res.data.dataList.length; i++) { if(res.data.dataList[i].page_id != 235){ // $scope._dataArray.splice(res.data.dataList.length, 0, res.data.dataList[i]); $scope._dataArray.push(res.data.dataList[i]); }else{ $scope.data_last_array = res.data.dataList[i]; } } if($scope.data_last_array != false){ $scope._dataArray.push($scope.data_last_array); } }else{ $scope._dataArray = res.data.dataList; } // $scope._dataArray = res.data.dataList; console.log("page data array :" , $scope._dataArray ,$scope.data_last_array ); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.refid); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend-collection .-recommend-collection[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend-collection .-recommend-collection[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.viewDataSize = function() { return -($(".item-collection").height() + 100); }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPagesListsB', function($rootScope, $routeParams) { var templateName = 'componentPagesListsB'; var componentMain = 'componentPages'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._dataArray = []; $scope.data_last_array = false; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { 'badge_id_array': [18] } var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('page/lists', dataSend, $scope).then(function(res) { if (res.ok === 1) { console.log("page data array :", res); if (CUR_THEME.shop_id() == 635) { for (var i = 0; i < res.data.dataList.length; i++) { if (res.data.dataList[i].page_id != 235) { $scope._dataArray.push(res.data.dataList[i]); } else { $scope.data_last_array = res.data.dataList[i]; } } if ($scope.data_last_array != false) { $scope._dataArray.push($scope.data_last_array); } } else { $scope._dataArray = res.data.dataList; } console.log("page data array :", $scope._dataArray, $scope.data_last_array); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } }; return promise; }); _ui_share_app.directive('componentParallaxBlock', function ($rootScope, $routeParams) { var templateName = 'componentParallaxBlock'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { img: '@img', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.directive('componentPleaseWaitMain', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentPleaseWaitMain'; var componentMain = 'componentPleaseWait'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; }; return promise; });_ui_share_app.directive('componentPleaseWaitTypeA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentPleaseWaitTypeA'; var componentMain = 'componentPleaseWait'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; }; return promise; });_ui_share_app.directive('componentPleaseWaitTypeB', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentPleaseWaitTypeB'; var componentMain = 'componentPleaseWait'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; }; return promise; });/*_ui_share_app.directive('componentFooter', function($rootScope, $routeParams) { var templateName = 'componentFooter'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id: '=', background: '@', primary: '@', secondary: '@', name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) {}; return promise; });*/ _ui_share_app.factory('$componentPopup', function componentPopup($routeParams, $timeout) { return });_ui_share_app.directive('componentPopupHomeVideo', function($rootScope, $routeParams) { var componentMain = 'componentPopup'; var componentChild = 'homevideo'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'height': '@height' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'home_video_play': '?homeVideoPlay', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.assetsPath = 'extensions/themes/assets/'; /* get shop data */ $scope.data_shop = []; $scope.getDataShop = function() { var d = {}; GAEAPI.get('shop/current', d).then(function(e) { if (e.ok == 1) { $scope.data_shop = e.data; } }); }; $scope.getDataShop(); $scope.videoActive = false; $scope.videoVisible = false; $scope.viewVideo = function() { $scope.videoActive = true; $scope.videoVisible = true; }; $scope.unViewVideo = function() { $scope.videoActive = false; $scope.videoVisible = false; }; }; return promise; });_ui_share_app.directive('componentPopupProductIdA', function($rootScope, $routeParams) { var componentMain = 'componentPopup'; var componentChild = 'productida'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { text: '@text', btnstyle: '@btnstyle', productid: '@productid', textstyle: '@textstyle', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getProductId = function(callback) { var product_id = 0; setTimeout(function() { console.log("getProductId : $scope.productid : ", $scope.productid); if ($scope.productid != undefined) { product_id = $scope.productid; callback(product_id); } else { var route_params_product_id_text = ""; var route_params_product_id = 0; if (typeof $routeParams.product_id !== 'undefined') { route_params_product_id_text = parseInt($routeParams.product_id); route_params_product_id = $routeParams.product_id; } if (typeof route_params_product_id_text == "number" && route_params_product_id_text > 0) { product_id = route_params_product_id_text; callback(product_id); } else { var route_params_product_id_split = route_params_product_id.split("-"); product_id = route_params_product_id_split[0]; callback(product_id); } } }, 100); }; $scope.dataProductId = []; $scope.getAPIProductId = function(product_id, callback) { var statusAPIProductId = false; var dataProductId = []; var dataSend = { 'txt_product_id': product_id }; console.log("getAPIProductId : dataSend : ", dataSend); GAEAPI.get('product/id', dataSend, $scope).then(function(output) { console.log("getAPIProductId : output : ", output); if (output.ok == 1) { statusAPIProductId = true; dataProductId = output.data; callback(statusAPIProductId, dataProductId); } else { callback(statusAPIProductId, dataProductId); } }); }; $scope.showDebug = function() { return (typeof $routeParams.debugpopup !== 'undefined') ? true : false; }; $scope.activateOverlayVids = function(code) { console.log("productida :code", code); if (code == "") { return; } angular.element('._set_' + $scope.productid).addClass('active'); document.body.style.overflow = 'hidden'; $scope.video_code = code; }; $scope.unActiveOverlayVids = function() { angular.element('._set_' + $scope.productid).removeClass('active'); document.body.style.overflow = 'auto'; $scope.video_code = ""; }; $scope.$watch('productid', function(newValue, oldValue) { if (!newValue) { return; } else { $scope.getProductId(function(product_id) { console.log("getProductId : product_id : ", product_id); $scope.productid = product_id; $scope.getAPIProductId(product_id, function(statusAPIProductId, dataProductId) { console.log("getProductId : getAPIProductId : statusAPIProductId : ", statusAPIProductId); console.log("getProductId : getAPIProductId : dataProductId : ", dataProductId); $scope.dataProductId = dataProductId; }); }); } }); }; return promise; });_ui_share_app.directive('componentPopupProductIdB', function($rootScope, $routeParams) { var componentMain = 'componentPopup'; var componentChild = 'productidb'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { text: '@text', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'button_video': '?buttonVideo', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.productid = $scope._getPostIdFromURL(); $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getDataArray = function(input_id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': input_id, }; GAEAPI.get('product/id', dataSend).then(function(e) { if (e.ok === 1) { $scope._dataArray = e.data; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope.productid); $scope.open = function(code) { $scope.video_code = code; $("._set_" + $scope.productid).addClass("active"); $("body").css("overflow", "hidden"); }; $scope.close = function() { $scope.video_code = ""; $("._set_" + $scope.productid).removeClass("active"); $("body").css("overflow", "auto"); }; $scope.load = function() { var data = true; if ($(".block_container").html() == undefined) { data = true; } else { data = false } return data; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPopupProductIframe', function($rootScope, $routeParams) { var componentMain = 'componentPopup'; var componentChild = 'productiframe'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { iframe: '@iframe', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.showDebug = function() { return (typeof $routeParams.debugpopup !== 'undefined') ? true : false; }; $scope.activateOverlayVids = function(code) { console.log("productida :code", code); if (code == "") { return; } angular.element('._set_').addClass('active'); document.body.style.overflow = 'hidden'; $scope.video_code = code; }; $scope.unActiveOverlayVids = function() { angular.element('._set_').removeClass('active'); document.body.style.overflow = 'auto'; $scope.video_code = ""; }; }; return promise; });_ui_share_app.factory('$componentPost', function componentPost($routeParams, $timeout) { return });_ui_share_app.directive('componentPostIdA', function($rootScope, $routeParams) { var templateName = 'componentPostIdA'; var componentMain = 'componentPost'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { blogid: '@blogid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataBlogId = []; $scope.dataBlogIdState = { load: false, done: false }; $scope.getBlog = function(inputBlogId) { $scope.dataBlogIdState = { load: true, done: false }; var filter_json_d = { 'blog_id_array': [inputBlogId], } var d = { 'cur_page': 1, 'per_page': 10, 'txt_filter_json': JSON.stringify(filter_json_d) }; GAEAPI.get('post/lists', d, $scope).then(function(e) { if (e.ok === 1) { $scope.dataBlogId = e.data.dataList; $scope.dataBlogIdState = { load: false, done: true }; } }); }; $scope.getBlog($scope.blogid); $scope._makeDate = function(dateStr) { return (dateStr != "") ? moment(parseInt(dateStr) * 1000).format('LL') : ""; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPostSlideTypeA', function($rootScope, $routeParams) { var templateName = 'componentPostSlideTypeA'; var componentMain = 'componentPost'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', margin: '@margin', text1: '@text1', text2: '@text2', text3: '@text3', iconsize: '@iconsize', iconnext: '@iconnext', iconback: '@iconback', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarousel = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: false, autoplay: true, autoplaySpeed: 4000, slidesToShow: 3, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 2, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }, 10); }; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'cur_page': 1, 'per_page': 20 }; console.log('dataSend_Product', dataSend); GAEAPI.get('post/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getProductArray(); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; });_ui_share_app.factory('$componentPostCard', function componentPostCard($routeParams, $timeout) { return });_ui_share_app.directive('componentPostCardA', function($rootScope, $routeParams) { var templateName = 'componentPostCardA'; var componentMain = 'componentPostCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '=datain', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.GETstylebutton($scope.stylebutton); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPostCardMain', function($rootScope, $routeParams) { var templateName = 'componentPostCardMain'; var componentMain = 'componentPostCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', dataout: '=datain', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; }); _ui_share_app.directive('componentPostFeature', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentPostFeature'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath:'@imgpath' }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.data = []; $scope.getData = function(){ var d = { 'cur_page': 1, 'per_page': 8, 'txt_filter_json': JSON.stringify({'badge_id_array':[16,18]}) }; GAEAPI.get('post/lists',d,$scope).then(function(e){ if(e.ok==1){ $scope.data = e.data.dataList; } }); }; if(!$scope.data.length){ $scope.getData(); } /* Init slider */ $scope.initSlider = function(){ var elementName = '.component_post_map[uid="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 3, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false }; optionsParmas.responsive = [ { breakpoint: 1200, settings: { slidesToShow: 2, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false, arrows: false, } } ]; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_post_map[uid="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_post_map[uid="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; /** * Check if object array available for "website application" or "Mobile application" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /** * Check if seo */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { $timeout(function(){ $scope.initSlider(); }, 300); }); $scope._makeDate = function(dateStr){ return (dateStr!="") ? moment(parseInt(dateStr) * 1000).format('LL') : ""; }; }; return promise; }); _ui_share_app.factory('$componentProduct', function componentProduct($routeParams, $timeout) { return });_ui_share_app.directive('componentProductBadgeIdA', function($rootScope, $routeParams) { var templateName = 'componentProductBadgeIdA'; var componentMain = 'componentProduct'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.DataProductBadgeId = []; $scope.DataProductBadgeIdState = { load: true, done: false }; $scope.GETDataProductBadgeId = function(id) { $scope.DataProductBadgeIdState.load = true; $scope.DataProductBadgeIdState.done = false; var dataSend = { 'cur_page': 1, 'per_page': 50, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [16, id] }) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.DataProductBadgeId = e.data.dataList; console.log("DataProductBadgeId : ", $scope.badgeid, " DATA ", e.data); } $scope.DataProductBadgeIdState.load = false; $scope.DataProductBadgeIdState.done = true; }); }; $scope.GETDataProductBadgeId($scope.badgeid); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductInCategoryIdTypeA', function($rootScope, $routeParams) { var templateName = 'componentProductInCategoryIdTypeA'; var componentMain = 'componentProduct'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { cardgrid: '@cardgrid', cardlist: '@cardlist', stylebutton: '@stylebutton', limitdata: '@limitdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.consoleLog = function(name, data) { var consoleState = false; if (consoleState) { console.log(name, data); } }; $scope.viewCard = 'grid'; $scope.curPage = 1; $scope.totalRows = 0; $scope.perPage = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? parseInt($scope.limitdata) : 4; $scope.badge = 0; $scope.txtSortby = "product_update_time_desc"; $scope.showLoadMore = false; $scope.dataLoadMore = false; $scope.dataRelation = []; $scope.dataProduct = []; $scope.dataProductStatus = { load: true, done: false }; $scope.createArrayReferralId = function(referral_id, callback) { $scope.consoleLog("createArrayReferralId : referral_id : ", referral_id); var array_referral = []; array_referral.push(referral_id); callback(array_referral); }; $scope.createArrayBadgeId = function(badge_id, callback) { $scope.consoleLog("createArrayBadgeId : badge_id : ", badge_id); var array_badge = []; array_badge.push(badge_id); callback(array_badge); }; $scope.getRelationInCategoryId = function(referral_id, callback) { var relationInCategoryStatus = false; var relationList = []; var dataSend = { 'txt_referral_id': referral_id }; $scope.consoleLog("getRelationInCategoryId : dataSend : ", dataSend); GAEAPI.get('referral/relation', dataSend, $scope).then(function(output) { $scope.consoleLog("getRelationInCategoryId : output : ", output); if (output.ok == 1) { relationList = output.data; callback(relationInCategoryStatus, relationList); } else { callback(relationInCategoryStatus, relationList); } }); }; $scope.getProductInCategoryId = function(cur_page, per_page, txt_sortby, array_referral, array_badge, callback) { var productInCategoryStatus = false; var productTotalRows = 0; var productList = []; var filter_json = { "referral_id_array_in": array_referral, "badge_id_array": array_badge } var dataSend = { 'cur_page': cur_page, 'per_page': per_page, 'txt_sortby': txt_sortby, 'txt_filter_json': JSON.stringify(filter_json), }; $scope.consoleLog("getProductInCategoryId : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { $scope.consoleLog("getProductInCategoryId : output : ", output); if (output.ok == 1) { productInCategoryStatus = $scope.stateMore(true); productTotalRows = output.data.total_rows; productList = output.data.dataList; callback(productInCategoryStatus, productTotalRows, productList); } else { callback(productInCategoryStatus, productTotalRows, productList); } }); }; $scope.stateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.stateMore = function(_load_in) { var State = _load_in; return State; }; $scope.getRelationInCategoryId(parseInt($scope.viewRouteParams().referral_id), function(relationInCategoryStatus, relationList) { $scope.consoleLog("createArrayReferralId : getRelationInCategoryId : relationInCategoryStatus : ", relationInCategoryStatus); $scope.consoleLog("createArrayReferralId : getRelationInCategoryId : relationList : ", relationList); $scope.dataRelation = relationList; }); $scope.getApi = function(cur_page, per_page) { $scope.createArrayReferralId(parseInt($scope.viewRouteParams().referral_id), function(array_referral) { $scope.consoleLog("createArrayReferralId : array_referral : ", array_referral); $scope.dataProductStatus = $scope.stateData(true, false); $scope.createArrayBadgeId($scope.badge, function(array_badge) { $scope.consoleLog("createArrayBadgeId : array_badge : ", array_badge); $scope.getProductInCategoryId(cur_page, per_page, $scope.txtSortby, array_referral, array_badge, function(productInCategoryStatus, productTotalRows, productList) { $scope.consoleLog("createArrayReferralId : getProductInCategoryId : productInCategoryStatus : ", productInCategoryStatus); $scope.consoleLog("createArrayReferralId : getProductInCategoryId : productList : ", productList); $scope.dataProduct = productList; $scope.consoleLog("createArrayReferralId : getProductInCategoryId : productTotalRows : ", productTotalRows); $scope.totalRows = productTotalRows; if (productList.length < productTotalRows) { $scope.showLoadMore = $scope.stateMore(true); } else { $scope.showLoadMore = $scope.stateMore(false); } $scope.dataProductStatus = $scope.stateData(false, true); }); }); }); }; $scope.getApi($scope.curPage, $scope.perPage); $scope.badgeData = function(badge_id) { $scope.curPage = 1; $scope.badge = badge_id; $scope.getApi($scope.curPage, $scope.perPage); }; $scope.cardView = function(status) { $scope.viewCard = status; }; $scope.sortData = function() { $scope.getApi(1, $scope.curPage * $scope.perPage); }; $scope.loadMore = function() { $scope.curPage++; $scope.dataLoadMore = $scope.stateMore(true); $scope.createArrayReferralId(parseInt($scope.viewRouteParams().referral_id), function(array_referral) { $scope.consoleLog("createArrayReferralId : array_referral : ", array_referral); $scope.createArrayBadgeId($scope.badge, function(array_badge) { $scope.getProductInCategoryId($scope.curPage, $scope.perPage, $scope.txtSortby, array_referral, array_badge, function(productInCategoryStatus, productTotalRows, productList) { $scope.consoleLog("createArrayReferralId : getProductInCategoryId : productInCategoryStatus : ", productInCategoryStatus); $scope.consoleLog("createArrayReferralId : getProductInCategoryId : productList : ", productList); var oldData = $scope.dataProduct; $scope.dataProduct = oldData.concat(productList); $scope.dataLoadMore = $scope.stateMore(false); $scope.consoleLog("createArrayReferralId : getProductInCategoryId : productTotalRows : ", productTotalRows); $scope.totalRows = productTotalRows; if ($scope.dataProduct.length < productTotalRows) { $scope.showLoadMore = $scope.stateMore(true); } else { $scope.showLoadMore = $scope.stateMore(false); } }); }); }); }; }; return promise; });_ui_share_app.directive('componentProductSetTypeA', function($rootScope, $routeParams) { var templateName = 'componentProductSetTypeA'; var componentMain = 'componentProduct'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { col: '@col', sortby: '@sortby', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', limitdata: '@limitdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 8; $scope._sortby = (typeof $scope.sortby !== 'undefined' && typeof $scope.sortby !== '') ? $scope.sortby : 'product_update_time_asc'; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope._showresult = (typeof $scope.showresult !== 'undefined' && typeof $scope.showresult !== '') ? $scope.showresult : true; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_sortby': $scope._sortby, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/set_lists', dataSend, $scope).then(function(output) { if (output.ok === 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._getProductArray(); }; return promise; });_ui_share_app.directive('componentProductSetTypeB', function($rootScope, $routeParams) { var templateName = 'componentProductSetTypeB'; var componentMain = 'componentProduct'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { col: '@col', sortby: '@sortby', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', limitdata: '@limitdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 100; $scope._sortby = (typeof $scope.sortby !== 'undefined' && typeof $scope.sortby !== '') ? $scope.sortby : 'product_update_time_asc'; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope._showresult = (typeof $scope.showresult !== 'undefined' && typeof $scope.showresult !== '') ? $scope.showresult : true; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_sortby': $scope._sortby, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/set_lists', dataSend, $scope).then(function(output) { if (output.ok === 1) { $scope._dataArray = output.data.dataList; console.log('dataSend_Product :ppp', $scope._dataArray); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._getProductArray(); $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best Seller"; break; default: str = "null"; break; } return str; }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; }; return promise; });_ui_share_app.directive('componentProductBadge', function ($rootScope, $routeParams) { var templateName = 'componentProductBadge'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'badge':'@badge', 'imgpath':'@imgpath', 'perpage':'@perpage', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._badge_id = $scope.badge; /* Watch badge parameter */ $scope.$watch('_badge_id',function(newValue,oldValue){ if(!newValue || newValue=="" || typeof newValue === 'undefined'){ return; } $scope.getData(newValue); }); /* * get product data by badge_id * @params badgeIdString (integer) * @return array */ $scope.dataArray = []; $scope.getData = function(badgeIdString){ var d = { 'cur_page':1, 'per_page':$scope.perpage, 'txt_json_filter': JSON.stringify({"badge_id_array":[16,18]}) }; GAEAPI.get('product/lists',d,$scope).then(function(e){ if(e.ok === 1){ $scope.dataArray = e.data.dataList; } }); }; }; return promise; }); _ui_share_app.directive('componentProductBadgeB', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductBadgeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', badgeid: '@badgeid', badgename: '@badgename', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) {}; promise.controller = function ($scope, $timeout, $interval, $q, $window, $location) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_share_host + templateName + '/'; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._featureList = []; $scope._featureListDone = false; $scope._featureNav = false; $scope._getFeatureList = function () { if ($scope.referralid == '0' || $scope.referralid == '') { var dataSend = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 100, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify([{'badge_id_array': [16]}]) }; var endPoint = 'referral/lists'; } else { var dataSend = { 'txt_referral_id': $scope.referralid }; var endPoint = 'referral/id'; } GAEAPI.get(endPoint, dataSend).then(function (e) { if (e.ok === 1) { if ($scope.referralid == '0' || $scope.referralid == '') { $scope._featureList = e.data.dataList; $scope._getProductByReferralId(e.data.dataList); } else { $scope._featureList = [e.data]; var arrData = [e.data]; $scope._getProductByReferralId(arrData); } } $scope._featureListDone = true; }); }; $scope._getProductByReferralId = function (objectReferralArray) { var ref = []; $scope._productFeatureList = []; if (objectReferralArray.length) { angular.forEach(objectReferralArray, function (item, key) { ref.push(parseInt(item.referral_id)); }); if (ref.length) { var jsonFilter = { 'referral_id_array': ref, 'badge_id_array': ($scope.category !== 'brand') ? [18] : [16,18] }; var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend).then(function (e) { if(e.ok == 1){ $scope._productFeatureList = e.data.dataList; } else { $scope._productFeatureList = []; } $scope._featureNav = ($scope._productFeatureList.length > 1) ? true : false; if ($scope._productFeatureList.length > 0) { $scope._makeProductToCarousel(); } $scope._makeProductHide(ref); }); } } }; $scope._getProductByBadgeId = function(badgeIdRequest){ var badgeInt = parseInt(badgeIdRequest); var jsonFilter = { 'badge_id_array': [16,badgeInt] }; var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend).then(function (e) { if(e.ok == 1){ $scope._productFeatureList = e.data.dataList; } else { $scope._productFeatureList = []; } $scope._featureNav = ($scope._productFeatureList.length > 1) ? true : false; if ($scope._productFeatureList.length > 0) { $scope._makeProductToCarousel(); } $scope._makeProductHide(badgeInt); }); }; $scope._getProductByBadgeId($scope.badgeid); $scope._makeProductToCarousel = function () { var elementName = '.proList[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, responsive: [ { breakpoint: 1200, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false } } ] }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._makeProductHide = function (i) { $timeout(function () { if(angular.element('[data-id="item-of-'+i+'"]').length <= 0){ angular.element('[data-referral-container="'+i+'"]').hide(); } }, 500); }; $scope._resetData = function () { $scope._featureList = []; $scope._featureListDone = false; }; $scope._slickGoLeft = function () { setTimeout(function () { $('.proList[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { setTimeout(function () { $('.proList[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope._productFeatureListNavHide = function (r) { return ($('[data-id="item-of-' + r + '""]').length > 1) ? false : true; }; $scope._productDetailGo = function (p, t) { if($scope.checkSeo()){ return window.location.href = 'product-detail/' + p + ((typeof t !== 'undefined') ? '-'+$scope.titleUrl(t) : ''); } return window.location.href = '#/product-detail/' + p + ((typeof t !== 'undefined') ? '-'+$scope.titleUrl(t) : ''); }; /* Process */ $scope._cartStatus = function (product_id) { var a = '_noCartStatus'; if (UiCart.delegate.product.isProgress(product_id)) { a = '_inProcess'; if (UiCart.delegate.product.isSelected(product_id)) { a = '_inCart'; } } else { if (UiCart.delegate.product.isSelected(product_id)) { a = '_inCart'; } } return a; }; $scope._buy = function (product_id, q) { if (!UiCustomerBox.delegate.get.isLogin()) { return UiCustomerBox.delegate.modal.openLoginForm(); } /* If Product Is Not In Cart && This Product Currenly Loading */ if (!UiCart.delegate.product.isSelected(product_id)) { /* If Not Loading or Processing */ if (!UiCart.delegate.product.isProgress(product_id)) { UiCart.delegate.product.add(product_id, q); console.log("Product Add:", product_id, q); } else { return UiCart.modal.open(); } } else { /* Open cart when already added */ return UiCart.modal.open(); } }; $scope._viewDetail = function(endPathString){ return (GURL.isHtml5Mode()) ? GURL.location.href = endPathString : window.location.href = endPathString; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentProductBadgeC', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductBadgeC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', badgeid: '@badgeid', badgename: '@badgename', buttonstyle: '@buttonstyle', badgename: '@badgename', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_share_host + templateName + '/'; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._featureList = []; $scope._featureListDone = false; $scope._featureNav = false; $scope._getFeatureList = function() { if ($scope.referralid == '0' || $scope.referralid == '') { var dataSend = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 100, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify([{ 'badge_id_array': [16] }]) }; var endPoint = 'referral/lists'; } else { var dataSend = { 'txt_referral_id': $scope.referralid }; var endPoint = 'referral/id'; } GAEAPI.get(endPoint, dataSend).then(function(e) { if (e.ok === 1) { if ($scope.referralid == '0' || $scope.referralid == '') { $scope._featureList = e.data.dataList; $scope._getProductByReferralId(e.data.dataList); } else { $scope._featureList = [e.data]; var arrData = [e.data]; $scope._getProductByReferralId(arrData); } } $scope._featureListDone = true; }); }; $scope._getProductByReferralId = function(objectReferralArray) { var ref = []; $scope._productFeatureList = []; if (objectReferralArray.length) { angular.forEach(objectReferralArray, function(item, key) { ref.push(parseInt(item.referral_id)); }); if (ref.length) { var jsonFilter = { 'referral_id_array': ref, 'badge_id_array': ($scope.category !== 'brand') ? [18] : [16, 18] }; var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { $scope._productFeatureList = e.data.dataList; } else { $scope._productFeatureList = []; } $scope._featureNav = ($scope._productFeatureList.length > 1) ? true : false; if ($scope._productFeatureList.length > 0) { $scope._makeProductToCarousel(); } $scope._makeProductHide(ref); }); } } }; $scope._getProductByBadgeId = function(badgeIdRequest) { var badgeInt = parseInt(badgeIdRequest); var jsonFilter = { 'badge_id_array': [16, badgeInt] }; var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'badge_sort_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { $scope._productFeatureList = e.data.dataList; } else { $scope._productFeatureList = []; } $scope._featureNav = ($scope._productFeatureList.length > 1) ? true : false; if ($scope._productFeatureList.length > 0) { $scope._makeProductToCarousel(); } $scope._makeProductHide(badgeInt); }); }; $scope._getProductByBadgeId($scope.badgeid); $scope._makeProductToCarousel = function() { var elementName = '.proList[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false } }] }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._makeProductHide = function(i) { $timeout(function() { if (angular.element('[data-id="item-of-' + i + '"]').length <= 0) { angular.element('[data-referral-container="' + i + '"]').hide(); } }, 500); }; $scope._resetData = function() { $scope._featureList = []; $scope._featureListDone = false; }; $scope._slickGoLeft = function() { setTimeout(function() { $('.proList[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { setTimeout(function() { $('.proList[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope._productFeatureListNavHide = function(r) { return ($('[data-id="item-of-' + r + '""]').length > 1) ? false : true; }; $scope._productDetailGo = function(p, t) { if ($scope.checkSeo()) { return window.location.href = 'product-detail/' + p + ((typeof t !== 'undefined') ? '-' + $scope.titleUrl(t) : ''); } return window.location.href = '#/product-detail/' + p + ((typeof t !== 'undefined') ? '-' + $scope.titleUrl(t) : ''); }; /* Process */ $scope._cartStatus = function(product_id) { var a = '_noCartStatus'; if (UiCart.delegate.product.isProgress(product_id)) { a = '_inProcess'; if (UiCart.delegate.product.isSelected(product_id)) { a = '_inCart'; } } else { if (UiCart.delegate.product.isSelected(product_id)) { a = '_inCart'; } } return a; }; $scope._buy = function(product_id, q) { if (!UiCustomerBox.delegate.get.isLogin()) { return UiCustomerBox.delegate.modal.openLoginForm(); } /* If Product Is Not In Cart && This Product Currenly Loading */ if (!UiCart.delegate.product.isSelected(product_id)) { /* If Not Loading or Processing */ if (!UiCart.delegate.product.isProgress(product_id)) { UiCart.delegate.product.add(product_id, q); console.log("Product Add:", product_id, q); } else { return UiCart.modal.open(); } } else { /* Open cart when already added */ return UiCart.modal.open(); } }; $scope._viewDetail = function(endPathString) { return (GURL.isHtml5Mode()) ? GURL.location.href = endPathString : window.location.href = endPathString; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductBadgeD', function($rootScope, $routeParams) { var templateName = 'componentProductBadgeD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { isRender: '=', name: '@name', productid: '@productid', showbutton: '@showbutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarouselProduct = function(elem) { console.debug('mkCarouselProduct: trigger'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { slidesToShow: 3, } }, { breakpoint: 767, settings: { slidesToShow: 2, } }, { breakpoint: 560, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._productArray = []; $scope._productArrayDone = false; $scope._getProductArray = function() { var jsonFilter = { 'badge_id_array': [16] }; var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'badge_sort_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._productArray = res.data.dataList; console.log('productArray', $scope._productArray); } }); }; $scope._getProductArray(); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.displayImage = function(image_url, prefix) {return GAEAPI.getGaeImageUrl(image_url, prefix);} }; return promise; });_ui_share_app.directive('componentProductBadgeE', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductBadgeE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'feature': '@feature', 'badgeid': '@badgeid', 'badgetext': '@badgetext', 'imgpath': '@imgpath', 'margin': '@margin', 'imgcart': '@imgcart', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval) { $scope.use_feature = (typeof $scope.feature !== 'undefined' && $scope.feature == 'true') ? true : false; /** * Check if object array available for "website application" or "Mobile application" or "Featured" * @params object array * return true | false (default) */ $scope.getData = function() { var data = { consoleLog: function(name, data) { /* console.log(name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(number, api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(number, api, dataSend); }, getApi: function(number, api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(number, output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrlProductDetail: function(product_id, product_title) { var _self = this; var url = 'product-detail/'; url += product_id + '-'; url += _self.titleUrl(product_title); _self.locationUrl(url, ''); }, locationUrl: function(url) { if (url != "") { $location.url(url).replace(); } }, windowLocation: function(url) { if (url != "") { window.location.href = url; } }, main: function() { var _self = this; } } return data; }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope._showFeature = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 16) { r = true; break; } } return r; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* Dummy */ $scope.getDummyArray = function() { var r = []; var max = 6; for (var i = 0; i < max; i++) { r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }], product_badge: [{ badge_id: 18 }], callback_array: true }); } return r; }; $scope.data = []; $scope.data_done = false; /* Get referral data (all) * @params none * @return array */ $scope.getData = function(badgeId) { $scope.data = []; $scope.data_done = false; var filterJson = { 'badge_id_array': [18, badgeId] }; if ($scope.use_feature) { filterJson.badge_id_array.push(16); } var d = { 'cur_page': 1, 'per_page': 8, 'txt_filter_json': JSON.stringify(filterJson), }; GAEAPI.get('product/lists', d, $scope).then(function(e) { if (e.ok == 1) { if (e.data.dataList.length > 0) { $scope.data = e.data.dataList; console.log("amatour : ", $scope.data); } else { // var dummy = $scope.getDummyArray(); // $scope.data = dummy; $scope.data = []; } $scope.data_done = true; } }); }; /* Get referral data (by referral_id) * @params id = referral_id * @return array */ // $scope.getDataReferral = function(id){ // $scope.data = []; // $scope.data_done = false; // var d = { // 'txt_referral_id':id // }; // GAEAPI.get('referral/id_map',d,$scope).then(function(e){ // if(e.ok == 1){ // $scope.data[0] = e.data; // $scope.data_done = true; // $scope.buildImageSlider($scope.data); // } // }); // }; /* * params listener * @params newValue * @params oldValue * @return function */ $scope.$watch('badgeid', function(newValue, oldValue) { if (!newValue) { return; } $scope.getData(newValue); }); /* * check if image array exist or build dummy image array * @params arrayObject = object array * @return array */ $scope.buildImageSlider = function() { var imageArray = function() { return [{ 'image_url': 'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1.jpg' }, /*{'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'},*/ ]; }; var imageBannerArray = function() { return [{ 'image_url': 'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1.jpg' }, /*{'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2.jpg'},*/ ]; }; angular.forEach($scope.data, function(item, key) { if (typeof item.product_image == 'undefined') { item.product_image = []; } /*if(typeof item.referral_image_banner == 'undefined'){ item.referral_image_banner = []; }*/ if (!item.product_image.length) { item.product_image = imageArray(); } /*item.referral_image_banner = imageBannerArray();*/ }); }; /* Make Carousel */ $scope._makeProductToCarousel = function(keyCustom) { var elementName = '[data-id="' + keyCustom + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, "", keyCustom); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function() { return "-" + (($('.row.slick-slider[data-id="' + $scope._uniqueKey + '"]').height() / 2) + 34) + "px"; }; /* Carousel Arrow Click */ $scope._slickGoLeft = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; /* Carousel Arrow Click */ $scope._slickGoRight = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { if ($('[data-id*="gallery-"]').length) { $('[data-id*="gallery-"]').not('.slick-initialized').each(function(Key, Object) { if ($(this).find('.imageItem').length > 0) { $scope._makeProductToCarousel($(this).attr('data-id')); } }); } }); /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductBadgeF', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductBadgeF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'feature':'@feature', 'badgeid':'@badgeid', 'badgetext':'@badgetext', 'imgpath':'@imgpath', 'margin':'@margin', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.use_feature = (typeof $scope.feature !== 'undefined' && $scope.feature == 'true') ? true : false; /** * Check if object array available for "website application" or "Mobile application" or "Featured" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope._showFeature = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 16) { r = true; break; } } return r; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* Dummy */ $scope.getDummyArray = function(){ var r = []; var max = 6; for(var i = 0; i < max; i++){ r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}], product_badge:[{badge_id:18}], callback_array:true }); } return r; }; $scope.data = []; $scope.data_done = false; /* Get referral data (all) * @params none * @return array */ $scope.getData = function(badgeId){ $scope.data = []; $scope.data_done = false; var filterJson = {'badge_id_array':[18, badgeId]}; var d = { 'cur_page':1, 'per_page':6, 'txt_filter_json':JSON.stringify(filterJson), }; GAEAPI.get('product/lists',d,$scope).then(function(e){ if(e.ok == 1){ if(e.data.dataList.length > 0){ $scope.data = e.data.dataList; var t = $interval(function () { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); } else { var dummy = $scope.getDummyArray(); $scope.data = dummy; } /*$scope.buildImageSlider($scope.data);*/ $scope.data_done = true; } /*console.log("getData",e);*/ }); }; /* Get referral data (by referral_id) * @params id = referral_id * @return array */ $scope.getDataReferral = function(id){ $scope.data = []; $scope.data_done = false; var d = { 'txt_referral_id':id }; GAEAPI.get('referral/id_map',d,$scope).then(function(e){ if(e.ok == 1){ $scope.data[0] = e.data; $scope.data_done = true; $scope.buildImageSlider($scope.data); } }); }; /* * params listener * @params newValue * @params oldValue * @return function */ $scope.$watch('badgeid', function (newValue, oldValue) { if (!newValue){ return; } $scope.getData(newValue); }); /* * check if image array exist or build dummy image array * @params arrayObject = object array * @return array */ $scope.buildImageSlider = function(){ var imageArray = function(){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1.jpg'}, /*{'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'},*/ ]; }; var imageBannerArray = function(){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1.jpg'}, /*{'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2.jpg'},*/ ]; }; angular.forEach($scope.data, function(item,key){ if(typeof item.product_image == 'undefined'){ item.product_image = []; } /*if(typeof item.referral_image_banner == 'undefined'){ item.referral_image_banner = []; }*/ if(!item.product_image.length){ item.product_image = imageArray(); } /*item.referral_image_banner = imageBannerArray();*/ }); }; /* Make Carousel */ $scope._makeProductToCarousel = function (keyCustom) { var elementName = '[data-id="' + keyCustom + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, "", keyCustom); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(){ return "-" + (($('.row.slick-slider[data-id="'+$scope._uniqueKey+'"]').height() / 2) + 34) + "px"; }; $scope.initSlider = function(){ var elementName = '.product_badge_slide[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, centerMode: true, centerPadding: '0px', slidesToShow: 3, slidesToScroll: 1, dots: false, arrows: false, infinite: true, responsive: [ { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 2 } } ] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { if($('[data-id*="gallery-"]').length){ $('[data-id*="gallery-"]').not('.slick-initialized').each(function(Key,Object){ if($(this).find('.imageItem').length > 0){ $scope._makeProductToCarousel($(this).attr('data-id')); } }); } }); $scope.slickGoLeft=function(){ setTimeout(function () { $('.product_badge_slide[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.product_badge_slide[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; $scope.getheigth =function(){ return (($('.product_badge_slide').height())/2)+"px"; } /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentProductBadgeG', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductBadgeG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'feature':'@feature', 'referralid':'@referralid', 'badgeid':'@badgeid', 'badgetext':'@badgetext', 'imgpath':'@imgpath', 'margin':'@margin', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval) { $scope.use_feature = (typeof $scope.feature !== 'undefined' && $scope.feature == 'true') ? true : false; /** * Check if object array available for "website application" or "Mobile application" or "Featured" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope._showFeature = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 16) { r = true; break; } } return r; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* Dummy */ $scope.getDummyArray = function(){ var r = []; var max = 6; for(var i = 0; i < max; i++){ r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}], product_badge:[{badge_id:18}], callback_array:true }); } return r; }; $scope.data = []; $scope.data_done = false; /* Get referral data (all) * @params none * @return array */ $scope.getData = function(referralId){ $scope.data = []; $scope.data_done = false; var filterJson = { 'badge_id_array':[18], 'referral_id_array':[referralId] }; if($scope.badgeid !== "" && $scope.badgeid != 0){ filterJson.badge_id_array.push($scope.badgeid); } var d = { 'cur_page':1, 'per_page':12, 'txt_filter_json':JSON.stringify(filterJson), }; GAEAPI.get('product/lists',d,$scope).then(function(e){ if(e.ok == 1){ if(e.data.dataList.length > 0){ $scope.data = e.data.dataList; } else { var dummy = $scope.getDummyArray(); $scope.data = dummy; } /*$scope.buildImageSlider($scope.data);*/ $scope.data_done = true; } /*console.log("getData",e);*/ }); }; /* Get referral data (by referral_id) * @params id = referral_id * @return array */ $scope.getDataReferral = function(id){ $scope.data = []; $scope.data_done = false; var d = { 'txt_referral_id':id }; GAEAPI.get('referral/id_map',d,$scope).then(function(e){ if(e.ok == 1){ $scope.data[0] = e.data; $scope.data_done = true; $scope.buildImageSlider($scope.data); } }); }; /* * params listener * @params newValue * @params oldValue * @return function */ $scope.$watch('referralid', function (newValue, oldValue) { if (!newValue){ return; } $scope.getData(newValue); }); /* * check if image array exist or build dummy image array * @params arrayObject = object array * @return array */ $scope.buildImageSlider = function(){ var imageArray = function(){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1.jpg'}, /*{'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'},*/ ]; }; var imageBannerArray = function(){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1.jpg'}, /*{'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2.jpg'},*/ ]; }; angular.forEach($scope.data, function(item,key){ if(typeof item.product_image == 'undefined'){ item.product_image = []; } /*if(typeof item.referral_image_banner == 'undefined'){ item.referral_image_banner = []; }*/ if(!item.product_image.length){ item.product_image = imageArray(); } /*item.referral_image_banner = imageBannerArray();*/ }); }; /* Make Carousel */ $scope._makeProductToCarousel = function (keyCustom) { var elementName = '[data-id="' + keyCustom + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, "", keyCustom); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(){ return "-" + (($('.row.slick-slider[data-id="'+$scope._uniqueKey+'"]').height() / 2) + 34) + "px"; }; /* Carousel Arrow Click */ $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; /* Carousel Arrow Click */ $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { if($('[data-id*="gallery-"]').length){ $('[data-id*="gallery-"]').not('.slick-initialized').each(function(Key,Object){ if($(this).find('.imageItem').length > 0){ $scope._makeProductToCarousel($(this).attr('data-id')); } }); } }); /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.filter('priceRange', function() { return function(arrayItems, rangeInfo) { return arrayItems.filter(function(item) { return (item.product_price >= rangeInfo.min && item.product_price <= rangeInfo.max); }); } }); _ui_share_app.directive('componentProductBrand', function($rootScope, $routeParams) { var templateName = 'componentProductBrand'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', _component: '@component', _limit: '@limit', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._getBrandIdFromURL = function() { var data_id = $scope.id; var a = $scope.id; if (typeof $routeParams.brand_id !== 'undefined') { test = parseInt($routeParams.brand_id); a = $routeParams.brand_id; } if (typeof data_id === 'number' && data_id > 0) { return data_id; } else { var b = a.split("-"); return b[0]; } }; $scope.menu_filter_price = [{ 'id': '0-500', 'name': "0 - 500" }, { 'id': '501-1000', 'name': "501 - 1,000" }, { 'id': '1001-1500', 'name': "1,001 - 1,500" }, { 'id': '1501-2000', 'name': "1,501 - 2,000" }, { 'id': '2001-2500', 'name': "2,001 - 2,500" }, { 'id': '2501-3000', 'name': "2,501 - 3,000" }, { 'id': '0-9999999', 'name': "ALL" }]; $scope.rangeInfo = { min: 0, max: 9999999 }; $scope.moreShow = true; $scope.showMore = function(total, data) { if (total <= data) { $scope.moreShow = false; } else { $scope.moreShow = true; } } $scope.priceBrand = function(p) { var a = p.split('-'); $("#price_" + p).prop("checked", true); $scope.rangeInfo.min = parseInt(a[0]); $scope.rangeInfo.max = parseInt(a[1]); } $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.product_badge_id = ""; $scope.products_lists_array = []; $scope._productBadgeArrayState = { load: false, done: false }; $scope.referral_lists_array = []; $scope.getReferralListsArray = function(brand_id) { var dataSend = { 'txt_referral_id': brand_id }; console.log("getReferralListsArray dataSend : ", dataSend); GAEAPI.get('referral/id', dataSend).then(function(output) { console.log("getReferralListsArray GAEAPI : get : output : ", output); if (output.ok == 1) { $scope.referral_lists_array = output.data; } }); }; $scope.getProductsListsArray = function(brand_id, cur, per) { if (brand_id != $scope.product_badge_id) { $scope.cur = 1; cur = 1; $scope.product_badge_id = brand_id; $scope.priceBrand("0-9999999"); } if (cur == 1) { $scope._productBadgeArrayState = $scope.StateData(true, false); } var filter_json = { "referral_id_array": [brand_id] } var dataSend = { 'cur_page': cur, 'per_page': per, 'txt_filter_json': JSON.stringify(filter_json) }; console.log("getProductsListsArray dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { console.log("getProductsListsArray GAEAPI : get : output : ", output); if (output.ok == 1) { $scope.$apply(function() { if ($scope.products_lists_array.length) { var curData = $scope.products_lists_array; var total = output.data.total_rows; $scope.products_lists_array = curData.concat(output.data.dataList); $scope.showMore(total, $scope.products_lists_array.length); } else { var curData = output.data.dataList; var total = output.data.total_rows; $scope.products_lists_array = output.data.dataList; $scope.showMore(total, $scope.products_lists_array.length); $scope.priceBrand("0-9999999"); } }); } if ($scope.cur > 1) { $scope.loadMore_is_load = false; } if (cur == 1) { $scope._productBadgeArrayState = $scope.StateData(false, true); } }); }; $scopeloadMore_is_load = false; $scope.cur = 1; $scope.limit = parseInt($scope._limit); $scope.loadMore = function() { $scope.cur++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getReferralListsArray($scope._getBrandIdFromURL()); $scope.getProductsListsArray($scope._getBrandIdFromURL(), $scope.cur, $scope.limit); }, 300); }; $scope.getReferralListsArray($scope._getBrandIdFromURL()); $scope.getProductsListsArray($scope._getBrandIdFromURL(), $scope.cur, $scope.limit); }; return promise; });_ui_share_app.factory('$componentProductCard', function componentProductCard($routeParams, $timeout) { return });_ui_share_app.directive('componentProductCardA', function($rootScope, $routeParams) { var templateName = 'componentProductCardA'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardAa', function($rootScope, $routeParams) { var templateName = 'componentProductCardAa'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardB', function($rootScope, $routeParams) { var templateName = 'componentProductCardB'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.button = ""; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardC', function($rootScope, $routeParams) { var templateName = 'componentProductCardC'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope._shop_id = CUR_THEME.shop_id(); $scope._currency = ($scope._shop_id == "635") ? 0 : 2; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } /* console.log('databutton : ', $scope.button); */ }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); /* console.log('productdata : item', $scope.item); */ }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.calculateDiscountTwo = function(expensivePrice, salePrice) { var dif = salePrice - parseInt(expensivePrice); var sum = parseInt(100 - ((dif * 100) / salePrice)); return (sum < 1) ? 1 : sum; }; $scope._calculateDiscount = function(discount, price) { var outPrice = 0; if (discount.discount_type_id == '101') { if (price > parseInt(discount.discount_price)) { outPrice = price - parseInt(discount.discount_price); } else { outPrice = price; } } else if (discount.discount_type_id == '102') { /* console.log("_calculateDiscount : ", discount, " price :", price); */ var percent = parseInt(discount.discount_percent) / 100; var pricePercent = percent * price; outPrice = price - pricePercent; } return outPrice; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardCa', function($rootScope, $routeParams) { var templateName = 'componentProductCardCa'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardCb', function($rootScope, $routeParams) { var templateName = 'componentProductCardCb'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardCb : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); res_jsonParse.product_price = (res_jsonParse.product_price == null) ? 0 : res_jsonParse.product_price; res_jsonParse.product_compare_price = (res_jsonParse.product_compare_price == null) ? 0 : res_jsonParse.product_compare_price; _self.checkAttribute(res_jsonParse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); if (res_attribute) { _self.checkPriceMin(res_jsonParse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); }) } else { var res_price = res_jsonParse.product_price; var res_compare_price = res_jsonParse.product_compare_price; _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); } }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardD', function($rootScope, $routeParams) { var templateName = 'componentProductCardD'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ /*case 16: str = "FEATURED"; break;*/ case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; /*case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break;*/ } return str; }; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } }; return promise; });_ui_share_app.directive('componentProductCardE', function($rootScope, $routeParams) { var templateName = 'componentProductCardE'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; /*case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break;*/ } return str; }; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } }; return promise; });_ui_share_app.directive('componentProductCardEa', function($rootScope, $routeParams) { var templateName = 'componentProductCardEa'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', view: '@view', imgcart: '@imgcart', styletext: '@styletext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.button = ($scope.stylebutton == undefined || $scope.stylebutton == "") ? "filled_button" : $scope.stylebutton; $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardEa : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); res_jsonParse.product_price = (res_jsonParse.product_price == null) ? 0 : res_jsonParse.product_price; res_jsonParse.product_compare_price = (res_jsonParse.product_compare_price == null) ? 0 : res_jsonParse.product_compare_price; _self.checkAttribute(res_jsonParse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); if (res_attribute) { _self.checkPriceMin(res_jsonParse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); }) } else { var res_price = res_jsonParse.product_price; var res_compare_price = res_jsonParse.product_compare_price; _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); } }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardF', function($rootScope, $routeParams) { var templateName = 'componentProductCardF'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', datafontcolor: '@datafontcolor', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.button = ""; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.getImageUrl = function(imgObj, preferSize) { if (window.devicePixelRatio >= 2) { return imgObj.image_url; } return "https://image.getappeasy.com/src/images/" + imgObj.image_file_dir + "t" + preferSize + "_" + imgObj.image_file_name; }; }; return promise; });_ui_share_app.directive('componentProductCardFa', function($rootScope, $routeParams) { var templateName = 'componentProductCardFa'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', datafontcolor: '@datafontcolor', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; /*case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break;*/ } return str; }; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } }; return promise; });_ui_share_app.directive('componentProductCardG', function($rootScope, $routeParams) { var templateName = 'componentProductCardG'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardGRelate', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductCardGRelate'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productid: '@productid', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.item = []; $scope._getDataArray = function(id) { console.log('productdata : item', id); var dataSend = { 'txt_product_id': id, }; GAEAPI.get('product/id', dataSend ,$scope).then(function(res) { if (res.ok === 1) { $scope.item = res.data; console.log('productdata : item', $scope.item); } }); }; $scope.$watch('productid', function (newValue, oldValue) { if (newValue){ $scope._getDataArray(newValue); }else{ return; } }); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardH', function($rootScope, $routeParams) { var templateName = 'componentProductCardH'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardHongmin', function($rootScope, $routeParams, $location) { var templateName = 'componentProductCardHongmin'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '@datashow', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = { name: "componentProductCardHongmin", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._back = ($scope.back != undefined && $scope.back != "") ? $scope.back : "default"; /* scope */ $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; _self.consoleLog("getRouteParams", "params", params); callback(params); }, getShopId: function(callback) { var _self = this; var shop_id = CUR_THEME.shop_id(); _self.consoleLog("getShopId", "shop_id", shop_id); callback(shop_id); }, setPageName: function(page_name, callback) { var _self = this; _self.consoleLog("setPageName", "page_name", page_name); callback(page_name); }, windowOpneBlank: function(url) { var _self = this; _self.consoleLog("windowOpneBlank", "url", url); if (url != '') { window.open(url, '_blank'); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = ""; _self.getRouteParams(function(params) { if ($scope._back == "store-lists") { page = page_name + "/" + id + "-" + name_url + "?back_page=" + $scope._back + "&data_page=" + params.staff_id; } else { page = page_name + "/" + id + "-" + name_url; } _self.locationUrlReplace(page); }); }, main: function() { var _self = this; } } return getFunction; }; $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, jsonParse: function(productdata, callback) { var _self = this; callback(JSON.parse(productdata)); }, formatDataSend: function(data_api, data_product, callback) { var _self = this; _self.consoleLog("formatDataSend", "data_api", data_api); _self.consoleLog("formatDataSend", "data_product", data_product); _self.jsonParse(data_product, function(res_data_product) { callback(data_api, res_data_product); }); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, checkLength: function(array, callback) { var _self = this; array = (array != undefined && array.length != 0); _self.consoleLog("checkLength", "array", array); callback(array); }, checkUndefined: function(object, callback) { var _self = this; object = (object != undefined); _self.consoleLog("checkUndefined", "object", object); callback(object); }, getMinPrice: function(variant_array, callback) { var _self = this; var res_product_id = { product_price: 0, product_compare_price: 0 }; angular.forEach(variant_array, function(item, index) { _self.toParseFloat(item.price, function(res_price) { if (res_product_id.product_price != 0) { if (res_price < res_product_id.product_price) { res_product_id.product_price = res_price; _self.toParseFloat(item.compare_price, function(res_compare_price) { res_product_id.product_compare_price = res_compare_price; }); } } else { res_product_id.product_price = (res_price != 0) ? res_price : res_product_id.product_price; _self.toParseFloat(item.compare_price, function(res_compare_price) { res_product_id.product_compare_price = res_compare_price; }); } }); }); _self.consoleLog("getMinPrice", "res_product_id", res_product_id); callback(res_product_id); }, checkAttribute: function(res_product_id, product_attribute, callback) { var _self = this; _self.checkLength(product_attribute, function(res_product_attribute) { if (res_product_attribute) { _self.checkUndefined(product_attribute.option_data, function(res_option_data) { if (res_option_data) { _self.checkLength(product_attribute.option_data.variant_array, function(res_variant_array) { if (res_variant_array) { _self.getMinPrice(product_attribute.option_data.variant_array, function(res_res_product_id_min) { res_product_id = res_res_product_id_min; }); } }); } }); } _self.consoleLog("checkAttribute", "res_product_id", res_product_id); callback(res_product_id); }); }, checkAttributes: function(product_price, product_compare_price, product_attribute, callback) { var _self = this; var res_product_id = { product_price: product_price, product_compare_price: product_compare_price }; _self.checkAttribute(res_product_id, product_attribute, function(res_product_id) { _self.consoleLog("checkAttributes", "res_product_id", res_product_id); callback(res_product_id); }); }, toParseFloat: function(number, callback) { var _self = this; number = parseFloat(number); _self.consoleLog("toParseFloat", "number", number); callback(number); }, checkNumberDecimal: function(number, callback) { var _self = this; _self.toParseFloat(number, function(res_number) { var res_state = (res_number % 1 == 0); _self.consoleLog("checkNumberDecimal", "res_state", res_state); callback(res_state); }); }, checkNumberDecimals: function(product_price, product_compare_price, callback) { var _self = this; var res_product_id = { product_price_decimal: 0, product_compare_price_decimal: 0 }; _self.checkNumberDecimal(product_price, function(res_price_decimal) { res_product_id.product_price_decimal = (res_price_decimal) ? 0 : 2; _self.checkNumberDecimal(product_compare_price, function(res_compare_price_decimal) { res_product_id.product_compare_price_decimal = (res_compare_price_decimal) ? 0 : 2; _self.consoleLog("checkNumberDecimals", "res_product_id", res_product_id); callback(res_product_id); }); }); }, checkDiscount: function(product_price, product_compare_price, product_discount, callback) { var _self = this; var res_product_id = { product_price: product_price, product_compare_price: product_compare_price }; _self.checkLength(product_discount, function(res_product_discount) { if (res_product_discount) { if (product_discount.discount_type_id == '101') { _self.toParseFloat(product_price, function(res_product_price) { _self.toParseFloat(product_discount.discount_price, function(res_discount_price) { res_product_id.product_price = res_product_price - res_discount_price; res_product_id.product_compare_price = res_product_price; }); }); } else if (product_discount.discount_type_id == '102') { _self.toParseFloat(product_price, function(res_product_price) { _self.toParseFloat(product_discount.discount_price, function(res_discount_price) { res_product_id.product_price = (res_product_price * ((100 - res_discount_price) / 100)); res_product_id.product_compare_price = res_product_price; }); }); } } _self.consoleLog("checkDiscount", "res_product_id", res_product_id); callback(res_product_id); }); }, main: function() { var _self = this; } } return getFunction; }; $scope.getReward = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, momentUnix: function(callback) { var _self = this; var now = moment().unix(); callback(now); }, getCalculator: function(product_price, reward, callback) { var _self = this; _self.consoleLog("getCalculator", "product_price", product_price); _self.consoleLog("getCalculator ", "reward", reward); var res_point_reward = 0; if (reward.type_id == "100") { res_point_reward = Math.floor((product_price / reward.reward_every_price)) * reward.reward_amount; } else if (reward.type_id == "101") { res_point_reward = reward.reward_amount; } else if (reward.type_id == "102") { res_point_reward = (reward.reward_percent * product_price) / 100; } else if (reward.type_id == "103") { res_point_reward = Math.floor((product_price / reward.reward_every_price)) * reward.reward_amount; } _self.consoleLog("getCalculator", "res_point_reward", res_point_reward); callback(res_point_reward); }, getProductReward: function(now, product_reward, callback) { var _self = this; var res_reward = { reward_length: (product_reward.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; res_reward.lifetime_time = now; if (res_reward.reward_length) { res_reward.lifetime_start_time = parseInt(product_reward.reward_lifetime.lifetime_start_time); res_reward.lifetime_end_time = parseInt(product_reward.reward_lifetime.lifetime_end_time); res_reward.type_id = product_reward.reward_type_id; res_reward.amount = parseInt(product_reward.reward_amount); res_reward.percent = parseInt(product_reward.reward_percent); res_reward.every_price = parseInt(product_reward.reward_every_price); } _self.consoleLog("getProductReward", "res_reward", res_reward); callback(res_reward); }, getPointConfig: function(now, shop_point_config, callback) { var _self = this; var res_reward = { reward_length: (shop_point_config != undefined && shop_point_config.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; res_reward.lifetime_time = now; if (res_reward.reward_length) { res_reward.lifetime_start_time = parseInt(shop_point_config.er_from); res_reward.lifetime_end_time = parseInt(shop_point_config.er_to); res_reward.type_id = "100"; res_reward.amount = parseInt(shop_point_config.er_earn); res_reward.every_price = parseInt(shop_point_config.er_rate); } _self.consoleLog("getPointConfig", "res_reward", res_reward); callback(res_reward); }, checkPointReward: function(reward, callback) { var _self = this; var state = false; if (reward.reward_length) { var start = reward.lifetime_start_time < reward.lifetime_time && reward.lifetime_start_time != 0; var end = (reward.lifetime_end_time != -1) ? reward.lifetime_time <= reward.lifetime_end_time && reward.lifetime_end_time != 0 : true; if (start && end) { if (reward.type_id == "100") { var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } else if (reward.type_id == "101") { var amount = reward.amount != 0; if (amount) { state = true; } } else if (reward.type_id == "102") { var percent = reward.percent != 0; if (percent) { state = true; } } else if (reward.type_id == "103") { var percent = reward.percent != 0; var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } } } callback(state); }, checkReward: function(rewardProduct, rewardPointConfig, callback) { var _self = this; _self.consoleLog("checkReward", "rewardProduct", rewardProduct); _self.consoleLog("checkReward", "rewardPointConfig", rewardPointConfig); var reward = { type_id: "0", amount: 0, percent: 0, every_price: 0 }; _self.checkPointReward(rewardProduct, function(res_state_product) { _self.checkPointReward(rewardPointConfig, function(res_state_point_config) { if (res_state_point_config) { reward.type_id = rewardPointConfig.type_id; reward.type_id = rewardPointConfig.type_id; reward.amount = rewardPointConfig.amount; reward.percent = rewardPointConfig.percent; reward.every_price = rewardPointConfig.every_price; } else if (res_state_product) { reward.type_id = rewardProduct.type_id; reward.amount = rewardProduct.amount; reward.percent = rewardProduct.percent; reward.every_price = rewardProduct.every_price; } _self.consoleLog("checkReward", "reward", reward); callback(reward); }); }); }, checkRewardType: function(product_reward, shop_point_config, callback) { var _self = this; _self.momentUnix(function(now) { _self.getProductReward(now, product_reward, function(res_reward_product) { _self.getPointConfig(now, shop_point_config, function(res_reward_point_config) { _self.checkReward(res_reward_product, res_reward_point_config, function(res_reward) { callback(res_reward); }); }); }); }); }, createReward: function(product_reward, shop_point_config, callback) { var _self = this; _self.consoleLog("createReward", "product_reward", product_reward); _self.consoleLog("createReward", "shop_point_config", shop_point_config); _self.checkRewardType(product_reward, shop_point_config, function(res_reward) { _self.consoleLog("createReward", "res_reward", res_reward); callback(res_reward); }); } } return getFunction; }; $scope.data_api = { product: { data_send: {}, api: "product/id", ok: false, data_array: {}, data_array_state: { load: false, done: false } }, shop_current: { data_send: {}, api: "shop/current", ok: false, data_array: {}, data_array_state: { load: false, done: false } } }; $scope.data_get = { reward: { quantity_name: 'reward', type_id: "0", reward_amount: 0, reward_percent: 0, reward_every_price: 0, point_reward: 0 } }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.data_array_state = state; _self.formatDataSend($scope.data_api.product, $scope.datashow, function(res_data_product, res_product) { _self.getNameUrl(res_product.product_title, function(res_title) { res_product.product_title_url = res_title; _self.checkAttributes(res_product.product_price, res_product.product_compare_price, res_product.product_attribute, function(res_product_id) { res_product.product_price = res_product_id.product_price; res_product.product_compare_price = res_product_id.product_compare_price; _self.checkDiscount(res_product.product_price, res_product.product_compare_price, res_product.product_discount, function(res_product_id_discount) { res_product.product_price = res_product_id_discount.product_price; res_product.product_compare_price = res_product_id_discount.product_compare_price; _self.checkNumberDecimals(res_product.product_price, res_product.product_compare_price, function(res_product_id_decimal) { res_product.product_price_decimal = res_product_id_decimal.product_price_decimal; res_product.product_compare_price_decimal = res_product_id_decimal.product_compare_price_decimal; res_data_product.data_array = res_product; _self.consoleLog("getApiData", "data_array", res_data_product.data_array); $scope.data_api.shop_current.data_array = ($scope.shopcurrent != undefined && $scope.shopcurrent != '') ? $scope.shopcurrent : {}; _self.consoleLog("getApiData", "shop_current", $scope.data_api.shop_current); $scope.getReward().createReward(res_data_product.data_array.product_reward, $scope.data_api.shop_current.data_array.shop_point_config, function(res_reward) { $scope.data_get.reward.type_id = res_reward.type_id; $scope.data_get.reward.reward_amount = res_reward.amount; $scope.data_get.reward.reward_percent = res_reward.percent; $scope.data_get.reward.reward_every_price = res_reward.every_price; $scope.getReward().getCalculator(res_product.product_price, $scope.data_get.reward, function(res_point_reward) { $scope.data_get.reward.point_reward = res_point_reward; }); }); }); }); }); }); }); }); }; return promise; });_ui_share_app.directive('componentProductCardI', function($rootScope, $routeParams) { var templateName = 'componentProductCardI'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardImage', function($rootScope, $routeParams) { var templateName = 'componentProductCardImage'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } }; return promise; });_ui_share_app.directive('componentProductCardJ', function($rootScope, $routeParams) { var templateName = 'componentProductCardJ'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } // console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price != undefined && compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; switch (r) { case 72: str = "เมนูใหม่"; break; case 74: str = "เมนูแนะนำ"; break; case 75: str = "เมนูขายดี"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeTypeUrl = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; if (CUR_THEME.shop_id() == "717") { switch (r) { case 72: str = "asset/icn-hm-badge3@2x.png"; break; case 74: str = "asset/icn-hm-badge2@2x.png"; break; case 75: str = "asset/icn-hm-badge1@2x.png"; break; default: str = "null"; break; } } return str; }; $scope.renderBadgeTypeImg = function() { var returnData = false; if (CUR_THEME.shop_id() == "717") { returnData = true; } else { returnData = false; } return returnData; }; $scope.renderBadgeClass = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; switch (r) { case 72: str = "NewArrival"; break; case 74: str = "Recommend"; break; case 75: str = "BestSeller"; break; default: str = "null"; break; } return str; }; }; return promise; });_ui_share_app.directive('componentProductCardK', function($rootScope, $routeParams) { var templateName = 'componentProductCardK'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.viewproduct = ($scope.view == undefined || $scope.view == "") ? 'grid' : $scope.view; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } // console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); // console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.dataCard = ""; $scope.dataVariantsPick = { pricefull: 0, calculate: 0 }; $scope._showData = function(data) { if (data.product_attribute != undefined) { if (data.product_attribute.option_data != undefined) { if (data.product_attribute.option_data.variant_array.length != undefined) { console.log("rovComponentProductCardA _showData data ELSE"); var variant_array = data.product_attribute.option_data.variant_array; console.log("rovComponentProductCardA _showData data variant_array :", variant_array); var product_price = 999999999; var product_compare_price = 0; for (var i = 0, l = variant_array.length; i < l; i++) { var price = parseInt(variant_array[i].price); var compare_price = parseInt(variant_array[i].compare_price); if (price != 0) { console.log("rovComponentProductCardA _showData data variant_array (product_price > variant_array[i].price)", product_price, price); if (product_price > price) { product_price = price; product_compare_price = compare_price; console.log("rovComponentProductCardA _showData data product_price :", product_price); } } } if (product_price == 999999999) { product_price = 0; } console.log("rovComponentProductCardA _showData data product_price product_compare_price end :", product_price, product_compare_price); $scope.item.product_price = product_price; $scope.item.product_compare_price = product_compare_price; } } } $scope.dataVariantsPick.pricefull = $scope.pricefull(data.product_price, data.product_compare_price, data.product_discount.discount_id, data.product_discount.discount_price, data.product_discount.discount_percent); $scope.dataVariantsPick.calculate = $scope.calculate(data.product_price, data.product_compare_price, data.product_discount.discount_id, data.product_discount.discount_price, data.product_discount.discount_percent); } $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; switch (r) { case 72: str = "เมนูใหม่"; break; case 74: str = "เมนูแนะนำ"; break; case 75: str = "เมนูขายดี"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeTypeUrl = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; if (CUR_THEME.shop_id() == "717") { switch (r) { case 72: str = "asset/icn-hm-badge3@2x.png"; break; case 74: str = "asset/icn-hm-badge2@2x.png"; break; case 75: str = "asset/icn-hm-badge1@2x.png"; break; default: str = "null"; break; } } return str; }; $scope.renderBadgeTypeImg = function() { var returnData = false; if (CUR_THEME.shop_id() == "717") { returnData = true; } else { returnData = false; } return returnData; }; $scope.renderBadgeClass = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "NewArrival"; break; case 74: str = "Recommend"; break; case 75: str = "BestSeller"; break; default: str = "null"; break; } return str; }; $scope._showData($scope.item); }; return promise; });_ui_share_app.directive('componentProductCardKa', function($rootScope, $routeParams) { var templateName = 'componentProductCardKa'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.viewproduct = ($scope.view == undefined || $scope.view == "") ? 'grid' : $scope.view; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } // console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); // console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.dataCard = ""; $scope.dataVariantsPick = { pricefull: 0, calculate: 0 }; $scope._showData = function(data) { if (data.product_attribute != undefined) { if (data.product_attribute.option_data != undefined) { if (data.product_attribute.option_data.variant_array.length != undefined) { console.log("rovComponentProductCardA _showData data ELSE"); var variant_array = data.product_attribute.option_data.variant_array; console.log("rovComponentProductCardA _showData data variant_array :", variant_array); var product_price = 999999999; var product_compare_price = 0; for (var i = 0, l = variant_array.length; i < l; i++) { var price = parseInt(variant_array[i].price); var compare_price = parseInt(variant_array[i].compare_price); if (price != 0) { console.log("rovComponentProductCardA _showData data variant_array (product_price > variant_array[i].price)", product_price, price); if (product_price > price) { product_price = price; product_compare_price = compare_price; console.log("rovComponentProductCardA _showData data product_price :", product_price); } } } console.log("rovComponentProductCardA _showData data product_price product_compare_price end :", product_price, product_compare_price); $scope.item.product_price = product_price; $scope.item.product_compare_price = product_compare_price; } } } $scope.dataVariantsPick.pricefull = $scope.pricefull(data.product_price, data.product_compare_price, data.product_discount.discount_id, data.product_discount.discount_price, data.product_discount.discount_percent); $scope.dataVariantsPick.calculate = $scope.calculate(data.product_price, data.product_compare_price, data.product_discount.discount_id, data.product_discount.discount_price, data.product_discount.discount_percent); } $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; switch (r) { case 72: str = "เมนูใหม่"; break; case 74: str = "เมนูแนะนำ"; break; case 75: str = "เมนูขายดี"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeTypeUrl = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; if (CUR_THEME.shop_id() == "717") { switch (r) { case 72: str = "asset/icn-hm-badge3@2x.png"; break; case 74: str = "asset/icn-hm-badge2@2x.png"; break; case 75: str = "asset/icn-hm-badge1@2x.png"; break; default: str = "null"; break; } } return str; }; $scope.renderBadgeTypeImg = function() { var returnData = false; if (CUR_THEME.shop_id() == "717") { returnData = true; } else { returnData = false; } return returnData; }; $scope.renderBadgeClass = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "NewArrival"; break; case 74: str = "Recommend"; break; case 75: str = "BestSeller"; break; default: str = "null"; break; } return str; }; $scope._showData($scope.item); $scope.checkout_note_status = false; $scope.saveProductNote = function(productId) { var product_note = $('#introdetail-' + productId).val(); return product_note; }; $scope.checkOutNote = function(productId) { var status = false; if ($scope.item.product_is_add_note == "1") { /* && $scope.dataVariantsPick.calculate >= 1 */ status = false; $("#intro-" + productId).addClass("active"); } else { status = true; } return status; } $scope.checkOut = function(productId, q) { if (UiCustomerBox.delegate.get.isLogin() == false) { return UiCustomerBox.delegate.modal.openLoginForm(); } else { var note = $scope.saveProductNote(productId); var status_note = $scope.checkOutNote(productId); console.log("checkOut() : note :", note, " status_note :", status_note); if (status_note == true) { /* && $scope.dataVariantsPick.calculate >= 1 */ window.location.href = GURL.base_url() + "checkout?pdata=" + productId + '-' + q + '-' + note; } } }; $scope.checkOutForm = function(productId, q) { if (UiCustomerBox.delegate.get.isLogin() == false) { return UiCustomerBox.delegate.modal.openLoginForm(); } else { var status_note = $scope.checkOutNote(productId); var status_note = true; if (status_note == true) { /* && $scope.dataVariantsPick.calculate >= 1 */ var note = $scope.saveProductNote(productId); window.location.href = GURL.base_url() + "checkout?pdata=" + productId + '-' + q + '-' + note; } } }; $scope.popupClose = function(productId) { $("#intro-" + productId).removeClass("active"); }; }; return promise; });_ui_share_app.directive('componentProductCardL', function($rootScope, $routeParams) { var templateName = 'componentProductCardL'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', imgpath : '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardM', function($rootScope, $routeParams) { var templateName = 'componentProductCardM'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'add': '?add', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardM : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; /* _self.consoleLog('jsonParse : productdata : ', productdata); */ callback(JSON.parse(productdata)); }, getNameUrl: function(name, callback) { var _self = this; var res_name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); res_name = res_name.split("--").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "res_name", res_name); callback(res_name); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_json_parse) { _self.getNameUrl(res_json_parse.product_title, function(product_title_url) { res_json_parse.product_title_url = product_title_url; _self.consoleLog('main : jsonParse : callback : res_json_parse : ', res_json_parse); res_json_parse.product_price = (res_json_parse.product_price == null) ? 0 : res_json_parse.product_price; res_json_parse.product_compare_price = (res_json_parse.product_compare_price == null) ? 0 : res_json_parse.product_compare_price; _self.checkAttribute(res_json_parse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_json_parse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); if (res_attribute) { _self.checkPriceMin(res_json_parse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_json_parse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_json_parse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_json_parse.product_price = res_check_discount_price; res_json_parse.product_compare_price = res_check_discount_compare_price; callback(res_json_parse); }); }); }); }) } else { var res_price = res_json_parse.product_price; var res_compare_price = res_json_parse.product_compare_price; _self.checkDiscountPrice(res_json_parse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_json_parse.product_price = res_check_discount_price; res_json_parse.product_compare_price = res_check_discount_compare_price; callback(res_json_parse); }); }); }); } }); }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red_product) { $scope.getFunction().consoleLog('main : callback : red_product : ', red_product); $scope.item = red_product; }); }; return promise; });_ui_share_app.directive('componentProductCardMaeju', function($rootScope, $routeParams) { var templateName = 'componentProductCardMaeju'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'add': '?add', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardMaeju : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); res_jsonParse.product_price = (res_jsonParse.product_price == null) ? 0 : res_jsonParse.product_price; res_jsonParse.product_compare_price = (res_jsonParse.product_compare_price == null) ? 0 : res_jsonParse.product_compare_price; _self.checkAttribute(res_jsonParse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); if (res_attribute) { _self.checkPriceMin(res_jsonParse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); }) } else { var res_price = res_jsonParse.product_price; var res_compare_price = res_jsonParse.product_compare_price; _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); } }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardMain', function($rootScope, $routeParams) { var templateName = 'componentProductCardMain'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', data: '@productdata', stylebutton: '@stylebutton', imgpath: '@imgpath', view: '@view', fontcolor: '@fontcolor', imgbutton: '@imgbutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.viewproduct = ($scope.view == undefined || $scope.view == "") ? 'grid' : $scope.view; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardO', function($rootScope, $routeParams) { var templateName = 'componentProductCardO'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', textbutton: '@textbutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardO : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); res_jsonParse.product_price = (res_jsonParse.product_price == null) ? 0 : res_jsonParse.product_price; res_jsonParse.product_compare_price = (res_jsonParse.product_compare_price == null) ? 0 : res_jsonParse.product_compare_price; _self.checkAttribute(res_jsonParse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); if (res_attribute) { _self.checkPriceMin(res_jsonParse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); }) } else { var res_price = res_jsonParse.product_price; var res_compare_price = res_jsonParse.product_compare_price; _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); } }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardOb', function($rootScope, $routeParams) { var templateName = 'componentProductCardOb'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', textbutton: '@textbutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.viewproduct = ($scope.view == undefined || $scope.view == "") ? 'grid' : $scope.view; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best Seller"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best Seller"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeClass = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "NewArrival"; break; case 74: str = "Recommend"; break; case 75: str = "BestSeller"; break; default: str = "null"; break; } return str; }; }; return promise; }); _ui_share_app.directive('componentProductCardOset', function($rootScope, $routeParams) { var templateName = 'componentProductCardOset'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', textbutton: '@textbutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.viewproduct = ($scope.view == undefined || $scope.view == "") ? 'grid' : $scope.view; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_percent == 0 && discount_price == 0) { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } else { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, product_price, compare_price, discount_type_id, discount_price, discount_percent) { var calculate = 0; if (discount_type_id != undefined) { if (discount_type_id == "101") { calculate = price - discount_price; } else if (discount_type_id == "102") { calculate = price - ((discount_percent / 100) * price); } else if (discount_type_id == "103") { calculate = product_price; } else { calculate = price; } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best Seller"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best Seller"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeClass = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "NewArrival"; break; case 74: str = "Recommend"; break; case 75: str = "BestSeller"; break; default: str = "null"; break; } return str; }; }; return promise; });_ui_share_app.directive('componentProductCardP', function($rootScope, $routeParams) { var templateName = 'componentProductCardP'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._stylebutton = ($scope.stylebutton == undefined || $scope.stylebutton == "") ? 'filled_button_round_small' : $scope.view; $scope._viewproduct = ($scope.view == undefined || $scope.view == "") ? 'grid' : $scope.view; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best Seller"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best Seller"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeClass = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "NewArrival"; break; case 74: str = "Recommend"; break; case 75: str = "BestSeller"; break; default: str = "null"; break; } return str; }; }; return promise; });_ui_share_app.directive('componentProductCardQ', function($rootScope, $routeParams) { var templateName = 'componentProductCardQ'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardQa', function($rootScope, $routeParams) { var templateName = 'componentProductCardQa'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardR', function($rootScope, $routeParams) { var templateName = 'componentProductCardR'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardRelateC', function($rootScope, $routeParams) { var templateName = 'componentProductCardRelateC'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardRelateD', function($rootScope, $routeParams) { var templateName = 'componentProductCardRelateD'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.button = ""; $scope.GETstylebutton = function(databutton) { console.log('databutton : ', databutton); if (databutton == undefined || databutton == "") { $scope.button = "filled_button"; } else { $scope.button = databutton; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardRelateUb', function($rootScope, $routeParams) { var templateName = 'componentProductCardRelateUb'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardRelateUb : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); for (var i = 0; i < variant.length; i++) { if (parseFloat(variant[i].price) != 0) { priceMin = parseFloat(variant[i].price); } } var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price) && parseFloat(variant[i].price) != 0) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); callback(res_jsonParse); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardS', function($rootScope, $routeParams) { var templateName = 'componentProductCardS'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardSiri', function($rootScope, $routeParams, $location) { var templateName = 'componentProductCardSiri'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', textbutton: '@textbutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardSiri : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrlProductDetail: function(product_id, product_title) { var _self = this; var url = 'product-detail/'; url += product_id + '-'; url += _self.titleUrl(product_title); _self.locationUrl(url, ''); }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); res_jsonParse.product_price = (res_jsonParse.product_price == null) ? 0 : res_jsonParse.product_price; res_jsonParse.product_compare_price = (res_jsonParse.product_compare_price == null) ? 0 : res_jsonParse.product_compare_price; _self.checkAttribute(res_jsonParse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); if (res_attribute) { _self.checkPriceMin(res_jsonParse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); }) } else { var res_price = res_jsonParse.product_price; var res_compare_price = res_jsonParse.product_compare_price; _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); } }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardStyle', function($rootScope, $routeParams) { var templateName = 'componentProductCardStyle'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', shopcurrent: '=shopcurrent', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'add': '?add', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope._component = { name: "componentProductCardStyle", show: (window.location.hostname == "localhost") ? true : false }; $scope.getReward = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, momentUnix: function(callback) { var _self = this; var now = moment().unix(); callback(now); }, getCalculator: function(product_price, reward, callback) { var _self = this; _self.consoleLog("getCalculator", "product_price", product_price); _self.consoleLog("getCalculator ", "reward", reward); var res_point_reward = 0; if (reward.type_id == "100") { res_point_reward = Math.floor((product_price / reward.reward_every_price)) * reward.reward_amount; } else if (reward.type_id == "101") { res_point_reward = reward.reward_amount; } else if (reward.type_id == "102") { res_point_reward = (reward.reward_percent * product_price) / 100; } else if (reward.type_id == "103") { res_point_reward = Math.floor((product_price / reward.reward_every_price)) * reward.reward_amount; } _self.consoleLog("getCalculator", "res_point_reward", res_point_reward); callback(res_point_reward); }, getProductReward: function(now, product_reward, callback) { var _self = this; var res_reward = { reward_length: (product_reward.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; res_reward.lifetime_time = now; if (res_reward.reward_length) { res_reward.lifetime_start_time = parseInt(product_reward.reward_lifetime.lifetime_start_time); res_reward.lifetime_end_time = parseInt(product_reward.reward_lifetime.lifetime_end_time); res_reward.type_id = product_reward.reward_type_id; res_reward.amount = parseInt(product_reward.reward_amount); res_reward.percent = parseInt(product_reward.reward_percent); res_reward.every_price = parseInt(product_reward.reward_every_price); } _self.consoleLog("getProductReward", "res_reward", res_reward); callback(res_reward); }, getPointConfig: function(now, shop_point_config, callback) { var _self = this; var res_reward = { reward_length: (shop_point_config != undefined && shop_point_config.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; res_reward.lifetime_time = now; if (res_reward.reward_length) { res_reward.lifetime_start_time = parseInt(shop_point_config.er_from); res_reward.lifetime_end_time = parseInt(shop_point_config.er_to); res_reward.type_id = "100"; res_reward.amount = parseInt(shop_point_config.er_earn); res_reward.every_price = parseInt(shop_point_config.er_rate); } _self.consoleLog("getPointConfig", "res_reward", res_reward); callback(res_reward); }, checkPointReward: function(reward, callback) { var _self = this; var state = false; if (reward.reward_length) { var start = reward.lifetime_start_time < reward.lifetime_time && reward.lifetime_start_time != 0; var end = (reward.lifetime_end_time != -1) ? reward.lifetime_time <= reward.lifetime_end_time && reward.lifetime_end_time != 0 : true; if (start && end) { if (reward.type_id == "100") { var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } else if (reward.type_id == "101") { var amount = reward.amount != 0; if (amount) { state = true; } } else if (reward.type_id == "102") { var percent = reward.percent != 0; if (percent) { state = true; } } else if (reward.type_id == "103") { var percent = reward.percent != 0; var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } } } _self.consoleLog("checkPointReward", "state", state); callback(state); }, checkReward: function(rewardProduct, rewardPointConfig, callback) { var _self = this; _self.consoleLog("checkReward", "rewardProduct", rewardProduct); _self.consoleLog("checkReward", "rewardPointConfig", rewardPointConfig); var reward = { type_id: "0", amount: 0, percent: 0, every_price: 0 }; _self.checkPointReward(rewardProduct, function(res_state_product) { _self.checkPointReward(rewardPointConfig, function(res_state_point_config) { if (res_state_point_config) { reward.type_id = rewardPointConfig.type_id; reward.type_id = rewardPointConfig.type_id; reward.amount = rewardPointConfig.amount; reward.percent = rewardPointConfig.percent; reward.every_price = rewardPointConfig.every_price; } else if (res_state_product) { reward.type_id = rewardProduct.type_id; reward.amount = rewardProduct.amount; reward.percent = rewardProduct.percent; reward.every_price = rewardProduct.every_price; } _self.consoleLog("checkReward", "reward", reward); callback(reward); }); }); }, checkRewardType: function(product_reward, shop_point_config, callback) { var _self = this; _self.momentUnix(function(now) { _self.getProductReward(now, product_reward, function(res_reward_product) { _self.getPointConfig(now, shop_point_config, function(res_reward_point_config) { _self.checkReward(res_reward_product, res_reward_point_config, function(res_reward) { callback(res_reward); }); }); }); }); }, createReward: function(product_reward, shop_point_config, callback) { var _self = this; _self.consoleLog("createReward", "product_reward", product_reward); _self.consoleLog("createReward", "shop_point_config", shop_point_config); _self.checkRewardType(product_reward, shop_point_config, function(res_reward) { _self.consoleLog("createReward", "res_reward", res_reward); callback(res_reward); }); } } return getFunction; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.data_api = { shop_current: { data_send: {}, api: "shop/current", ok: false, data_array: {}, data_array_state: { load: false, done: false } } }; $scope.data_get = { reward: { quantity_name: 'reward', type_id: "0", reward_amount: 0, reward_percent: 0, reward_every_price: 0, point_reward: 0 } }; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardStyle : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); res_jsonParse.product_price = (res_jsonParse.product_price == null) ? 0 : res_jsonParse.product_price; res_jsonParse.product_compare_price = (res_jsonParse.product_compare_price == null) ? 0 : res_jsonParse.product_compare_price; _self.checkAttribute(res_jsonParse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); $scope.data_api.shop_current.data_array = ($scope.shopcurrent != undefined && $scope.shopcurrent != '') ? $scope.shopcurrent : {}; if (res_attribute) { _self.checkPriceMin(res_jsonParse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; $scope.getReward().createReward(res_jsonParse.product_reward, $scope.data_api.shop_current.data_array.shop_point_config, function(res_reward) { $scope.data_get.reward.type_id = res_reward.type_id; $scope.data_get.reward.reward_amount = res_reward.amount; $scope.data_get.reward.reward_percent = res_reward.percent; $scope.data_get.reward.reward_every_price = res_reward.every_price; $scope.getReward().getCalculator(res_jsonParse.product_price, $scope.data_get.reward, function(res_point_reward) { $scope.data_get.reward.point_reward = res_point_reward; callback(res_jsonParse); }); }); }); }); }); }) } else { var res_price = res_jsonParse.product_price; var res_compare_price = res_jsonParse.product_compare_price; _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; $scope.getReward().createReward(res_jsonParse.product_reward, $scope.data_api.shop_current.data_array.shop_point_config, function(res_reward) { $scope.data_get.reward.type_id = res_reward.type_id; $scope.data_get.reward.reward_amount = res_reward.amount; $scope.data_get.reward.reward_percent = res_reward.percent; $scope.data_get.reward.reward_every_price = res_reward.every_price; $scope.getReward().getCalculator(res_jsonParse.product_price, $scope.data_get.reward, function(res_point_reward) { $scope.data_get.reward.point_reward = res_point_reward; callback(res_jsonParse); }); }); }); }); }); } }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardT', function($rootScope, $routeParams) { var templateName = 'componentProductCardT'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardTypeA', function($rootScope, $routeParams) { var templateName = 'componentProductCardTypeA'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '=datain', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.dataCard = ""; $scope.dataVariantsPick = { pricefull: 0, calculate: 0 }; $scope._showData = function(data) { if (data.product_attribute != undefined) { if (data.product_attribute.option_data != undefined) { if (data.product_attribute.option_data.variant_array.length != undefined) { console.log("rovComponentProductCardA _showData data ELSE"); var variant_array = data.product_attribute.option_data.variant_array; console.log("rovComponentProductCardA _showData data variant_array :", variant_array); var product_price = 999999999; var product_compare_price = 0; for (var i = 0, l = variant_array.length; i < l; i++) { var price = parseInt(variant_array[i].price); var compare_price = parseInt(variant_array[i].compare_price); if (price != 0) { console.log("rovComponentProductCardA _showData data variant_array (product_price > variant_array[i].price)", product_price, price); if (product_price > price) { product_price = price; product_compare_price = compare_price; console.log("rovComponentProductCardA _showData data product_price :", product_price); } } } console.log("rovComponentProductCardA _showData data product_price product_compare_price end :", product_price, product_compare_price); $scope.datashow.product_price = product_price; $scope.datashow.product_compare_price = product_compare_price; } } } $scope.dataVariantsPick.pricefull = $scope.pricefull(data.product_price, data.product_compare_price, data.product_discount.discount_id, data.product_discount.discount_price, data.product_discount.discount_percent); $scope.dataVariantsPick.calculate = $scope.calculate(data.product_price, data.product_compare_price, data.product_discount.discount_id, data.product_discount.discount_price, data.product_discount.discount_percent); } $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best seller"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeTypeUrl = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; if (CUR_THEME.shop_id() == "717") { switch (r) { case 72: str = "asset/icn-hm-badge1@2x.png"; break; case 74: str = "asset/icn-hm-badge2@2x.png"; break; case 75: str = "asset/icn-hm-badge3@2x.png"; break; default: str = "null"; break; } } return str; }; $scope.renderBadgeTypeImg = function() { var returnData = false; if (CUR_THEME.shop_id() == "717") { returnData = true; } else { returnData = false; } return returnData; }; $scope.renderBadgeClass = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; switch (r) { case 72: str = "NewArrival"; break; case 74: str = "Recommend"; break; case 75: str = "BestSeller"; break; default: str = "null"; break; } return str; }; $scope._showData($scope.datashow); }; return promise; });_ui_share_app.directive('componentProductCardU', function($rootScope, $routeParams) { var templateName = 'componentProductCardU'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('componentProductCardU : item', $scope.item); $scope.priceShow = 0; $scope.controlPrice = function(data_in) { console.log('controlPrice : data_in : ', data_in); console.log('controlPrice : data_in.product_attribute : ', data_in.product_attribute); console.log('controlPrice : data_in.product_attribute : length : ', data_in.product_attribute.length); if (data_in.product_attribute.length != 0) { console.log('controlPrice : data_in.product_attribute : length : if : ', ' if '); console.log('controlPrice : data_in.product_attribute.option_data : ', data_in.product_attribute.option_data); console.log('controlPrice : data_in.product_attribute.option_data : length : ', data_in.product_attribute.option_data.length); if (data_in.product_attribute.option_data.length != 0) { console.log('controlPrice : data_in.product_attribute.option_data : length : if : ', ' if ', ' if '); console.log('controlPrice : data_in.product_attribute.option_data.variant_array : ', data_in.product_attribute.option_data.variant_array); console.log('controlPrice : data_in.product_attribute.option_data.variant_array : length : ', data_in.product_attribute.option_data.variant_array.length); if (data_in.product_attribute.option_data.variant_array.length != 0) { var price = 0; var number = 0; for (var i = 0; data_in.product_attribute.option_data.variant_array.length > i; i++) { var _price_ = parseInt(data_in.product_attribute.option_data.variant_array[i].price); if (_price_ != 0) { if (number == 0) { $scope.priceShow = parseInt(data_in.product_attribute.option_data.variant_array[i].price); number++; } else { if ($scope.priceShow > _price_) { $scope.priceShow = parseInt(data_in.product_attribute.option_data.variant_array[i].price); number++; } } } console.log('controlPrice : data_in.product_attribute.option_data.variant_array[i].price : ', data_in.product_attribute.option_data.variant_array[i].price); } if ($scope.priceShow == 0) { $scope.priceShow = parseInt(data_in.product_price); } } else { $scope.priceShow = parseInt(data_in.product_price); } } else { $scope.priceShow = parseInt(data_in.product_price); } } else { $scope.priceShow = parseInt(data_in.product_price); } }; $scope.$watch('item', function(newValue, oldValue) { console.log('watch : newValue : ', newValue); if (newValue) { $scope.controlPrice(newValue); } else { return; } }); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardUb', function($rootScope, $routeParams) { var templateName = 'componentProductCardUb'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardUb : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { /* console.log(component, name, data); */ }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); for (var i = 0; i < variant.length; i++) { if (parseFloat(variant[i].price) != 0) { priceMin = parseFloat(variant[i].price); } } var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price) && parseFloat(variant[i].price) != 0) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); res_jsonParse.product_price = (res_jsonParse.product_price == null) ? 0 : res_jsonParse.product_price; res_jsonParse.product_compare_price = (res_jsonParse.product_compare_price == null) ? 0 : res_jsonParse.product_compare_price; _self.checkAttribute(res_jsonParse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); if (res_attribute) { _self.checkPriceMin(res_jsonParse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); }) } else { var res_price = res_jsonParse.product_price; var res_compare_price = res_jsonParse.product_compare_price; _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); } }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardUbRelate', function($rootScope, $routeParams) { var templateName = 'componentProductCardUbRelate'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productid: '@productid', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.item = []; $scope._getDataArray = function(id) { console.log('productdata : item', id); var dataSend = { 'txt_product_id': id, }; GAEAPI.get('product/id', dataSend ,$scope).then(function(res) { if (res.ok === 1) { $scope.item = res.data; console.log('productdata : item', $scope.item); } }); }; $scope.$watch('productid', function (newValue, oldValue) { if (newValue){ $scope._getDataArray(newValue); }else{ return; } }); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductCardUc', function($rootScope, $routeParams) { var templateName = 'componentProductCardUc'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardUf', function($rootScope, $routeParams) { var templateName = 'componentProductCardUf'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', fontcolor: '@fontcolor', imgbutton: '@imgbutton', databutton: '@databutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.item = JSON.parse($scope.productdata); $scope._databutton = $scope.databutton?$scope.databutton:'filled_button_small'; console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardUg', function($rootScope, $routeParams) { var templateName = 'componentProductCardUg'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardUg : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); res_jsonParse.product_price = (res_jsonParse.product_price == null) ? 0 : res_jsonParse.product_price; res_jsonParse.product_compare_price = (res_jsonParse.product_compare_price == null) ? 0 : res_jsonParse.product_compare_price; _self.checkAttribute(res_jsonParse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); if (res_attribute) { _self.checkPriceMin(res_jsonParse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); }) } else { var res_price = res_jsonParse.product_price; var res_compare_price = res_jsonParse.product_compare_price; _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); } }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardV', function($rootScope, $routeParams) { var templateName = 'componentProductCardV'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardVono', function($rootScope, $routeParams, $location) { var templateName = 'componentProductCardVono'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { item: '=item', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = { name: "componentProductCardVono", show: (window.location.hostname == "localhost") ? true : false }; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if (vm.component.show) { console.log(vm.component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getShopId: function(callback) { var _self = this; var shop_id = CUR_THEME.shop_id(); _self.consoleLog("getShopId", "shop_id", shop_id); callback(shop_id); }, setPageName: function(page_name, callback) { var _self = this; _self.consoleLog("setPageName", "page_name", page_name); callback(page_name); }, windowOpneBlank: function(url) { var _self = this; _self.consoleLog("windowOpneBlank", "url", url); if (url != '') { window.open(url, '_blank'); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); }, main: function() { var _self = this; } } return getFunction; }; $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, toParseFloat: function(number, callback) { var _self = this; number = parseFloat(number); _self.consoleLog("toParseFloat", "number", number); callback(number); }, checkLength: function(array, callback) { var _self = this; array = (array != undefined && array.length != 0); _self.consoleLog("checkLength", "array", array); callback(array); }, checkUndefined: function(object, callback) { var _self = this; object = (object != undefined); _self.consoleLog("checkUndefined", "object", object); callback(object); }, getMinPrice: function(variant_array, callback) { var _self = this; var res_product_id = { product_price: 0, product_compare_price: 0 }; angular.forEach(variant_array, function(item, index) { _self.toParseFloat(item.price, function(res_price) { if (res_product_id.product_price != 0) { if (res_price < res_product_id.product_price) { res_product_id.product_price = res_price; _self.toParseFloat(item.compare_price, function(res_compare_price) { res_product_id.product_compare_price = res_compare_price; }); } } else { res_product_id.product_price = (res_price != 0) ? res_price : res_product_id.product_price; _self.toParseFloat(item.compare_price, function(res_compare_price) { res_product_id.product_compare_price = res_compare_price; }); } }); }); _self.consoleLog("getMinPrice", "res_product_id", res_product_id); callback(res_product_id); }, checkAttribute: function(res_product_id, product_attribute, callback) { var _self = this; _self.checkLength(product_attribute, function(res_product_attribute) { if (res_product_attribute) { _self.checkUndefined(product_attribute.option_data, function(res_option_data) { if (res_option_data) { _self.checkLength(product_attribute.option_data.variant_array, function(res_variant_array) { if (res_variant_array) { _self.getMinPrice(product_attribute.option_data.variant_array, function(res_res_product_id_min) { res_product_id = res_res_product_id_min; }); } }); } }); } _self.consoleLog("checkAttribute", "res_product_id", res_product_id); callback(res_product_id); }); }, checkAttributes: function(product_price, product_compare_price, product_attribute, callback) { var _self = this; var res_product_id = { product_price: product_price, product_compare_price: product_compare_price }; _self.checkAttribute(res_product_id, product_attribute, function(res_product_id) { _self.consoleLog("checkAttributes", "res_product_id", res_product_id); callback(res_product_id); }); }, checkDiscount: function(product_price, product_compare_price, product_discount, callback) { var _self = this; var res_product_id = { product_price: product_price, product_compare_price: product_compare_price }; _self.checkLength(product_discount, function(res_product_discount) { if (res_product_discount) { if (product_discount.discount_type_id == '101') { _self.toParseFloat(product_price, function(res_product_price) { _self.toParseFloat(product_discount.discount_price, function(res_discount_price) { res_product_id.product_price = res_product_price - res_discount_price; res_product_id.product_compare_price = res_product_price; }); }); } else if (product_discount.discount_type_id == '102') { _self.toParseFloat(product_price, function(res_product_price) { _self.toParseFloat(product_discount.discount_percent, function(res_discount_percent) { res_product_id.product_price = (res_product_price * ((100 - res_discount_percent) / 100)); res_product_id.product_compare_price = res_product_price; }); }); } } _self.consoleLog("checkDiscount", "res_product_id", res_product_id); callback(res_product_id); }); }, main: function() { var _self = this; _self.consoleLog("main", "item", $scope.item); _self.checkAttributes( $scope.item.product_price, $scope.item.product_compare_price, $scope.item.product_attribute, function(res_product_id) { $scope.item.product_price = res_product_id.product_price; $scope.item.product_compare_price = res_product_id.product_compare_price; _self.checkDiscount( $scope.item.product_price, $scope.item.product_compare_price, $scope.item.product_discount, function(res_product_id_discount) { $scope.item.product_price = res_product_id_discount.product_price; $scope.item.product_compare_price = res_product_id_discount.product_compare_price; }); }); } } return getFunction; }; $scope.getData().main(); }; return promise; });_ui_share_app.directive('componentProductCardW', function($rootScope, $routeParams) { var templateName = 'componentProductCardW'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', view: '@view', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'add': '?add', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.viewproduct = ($scope.view == undefined || $scope.view == "") ? 'grid' : $scope.view; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope.returnDatatoJson = function(data) { $scope.item = JSON.parse(data); console.log('productdata : item', $scope.item); }; $scope.returnDatatoJson($scope.productdata); $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best Seller"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "New Arrival"; break; case 74: str = "Recommend"; break; case 75: str = "Best Seller"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeClass = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "NewArrival"; break; case 74: str = "Recommend"; break; case 75: str = "BestSeller"; break; default: str = "null"; break; } return str; }; }; return promise; });_ui_share_app.directive('componentProductCardX', function($rootScope, $routeParams) { var templateName = 'componentProductCardX'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.productdata); console.log('productdata : item', $scope.item); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentProductCardY', function($rootScope, $routeParams, $location) { var templateName = 'componentProductCardY'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._view = ($scope.view == "" || $scope.view == undefined) ? 'grid' : $scope.view; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.buildTitleUrl = function(str) { var res = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return res; }; $scope.dataprice = [{ price_name: 'product_price', price: 0, price_ecimals: 0 }, { price_name: 'product_compare_price', price: 0, price_ecimals: 0 }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var _self = this; var component = "componentProductCardY : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, numberIncludes: function(number, includes, callback) { var _self = this; var numberToString = (number == null) ? 0 : number; _self.consoleLog('numberIncludes : number : ', number); callback(numberToString.toString().includes(includes)); }, checkPrice: function(number, callback) { var _self = this; _self.consoleLog('checkPrice : number : ', number); _self.numberIncludes(number, '.', function(res) { _self.consoleLog('checkPrice : callback : res : ', res); callback((!res) ? 0 : 2); }); }, checkAttributeOptionVariant: function(variant, callback) { var _self = this; callback((variant.length == 0) ? false : true); }, checkAttributeOption: function(option, callback) { var _self = this; option.variant_array = (option.length == 0) ? [] : option.variant_array; _self.checkAttributeOptionVariant(option.variant_array, function(res_option) { callback((option.length == 0) ? false : res_option); }); }, checkAttribute: function(attribute, callback) { var _self = this; attribute.option_data = (attribute.length == 0) ? [] : attribute.option_data; _self.checkAttributeOption(attribute.option_data, function(res_attribute) { callback((attribute.length == 0) ? false : res_attribute); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, checkDiscountPrice: function(productDiscount, res_price, res_compare_price, callback) { var _self = this; var price = 0; var compare_price = 0; _self.consoleLog('checkDiscountPrice : productDiscount : ', productDiscount); _self.consoleLog('checkDiscountPrice : res_price : ', res_price); _self.consoleLog('checkDiscountPrice : res_compare_price : ', res_compare_price); if (productDiscount.length == 0) { _self.consoleLog('checkDiscountPrice : productDiscount.length : 0 ', productDiscount.length); price = parseFloat(res_price); compare_price = parseFloat(res_compare_price); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(res_price) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(res_price); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(res_price) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(res_price); } } callback(price, compare_price); }, jsonParse: function(productdata, callback) { var _self = this; _self.consoleLog('jsonParse : productdata : ', productdata); callback(JSON.parse(productdata)); }, main: function(productdata, callback) { var _self = this; _self.jsonParse(productdata, function(res_jsonParse) { _self.consoleLog('main : jsonParse : callback : res_jsonParse : ', res_jsonParse); res_jsonParse.product_price = (res_jsonParse.product_price == null) ? 0 : res_jsonParse.product_price; res_jsonParse.product_compare_price = (res_jsonParse.product_compare_price == null) ? 0 : res_jsonParse.product_compare_price; _self.checkAttribute(res_jsonParse.product_attribute, function(res_attribute) { _self.consoleLog('main : checkAttribute : callback : res_attribute : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : callback : res_attribute : ', res_attribute); if (res_attribute) { _self.checkPriceMin(res_jsonParse.product_attribute.option_data.variant_array, function(res_price, res_compare_price) { _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : product_id ', res_jsonParse.product_id); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_price : ', res_price); _self.consoleLog('main : checkAttribute : checkPriceMin : callback : res_compare_price : ', res_compare_price); _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); }) } else { var res_price = res_jsonParse.product_price; var res_compare_price = res_jsonParse.product_compare_price; _self.checkDiscountPrice(res_jsonParse.product_discount, res_price, res_compare_price, function(res_check_discount_price, res_check_discount_compare_price) { _self.checkPrice(res_check_discount_price, function(res_check_price) { _self.checkPrice(res_check_discount_compare_price, function(res_check_compare_price) { $scope.dataprice[0].price = res_check_discount_price; $scope.dataprice[0].price_ecimals = res_check_price; $scope.dataprice[1].price = res_check_discount_compare_price; $scope.dataprice[1].price_ecimals = res_check_compare_price; res_jsonParse.product_price = res_check_discount_price; res_jsonParse.product_compare_price = res_check_discount_compare_price; callback(res_jsonParse); }); }); }); } }); }); } }; return getFunction; }; $scope.getFunction().main($scope.productdata, function(red) { $scope.getFunction().consoleLog('main : callback : res : ', red); $scope.getFunction().consoleLog('main : callback : dataprice : ', $scope.dataprice); $scope.item = red; }); }; return promise; });_ui_share_app.directive('componentProductCardYa', function($rootScope, $routeParams, $location) { var templateName = 'componentProductCardYa'; var componentMain = 'componentProductCard'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productdata: '@productdata', stylebutton: '@stylebutton', dataview: '@dataview', view: '@view', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.shop_id = CUR_THEME.shop_id(); $scope.getData = function() { var data = { titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrlProductDetail: function(product_id, product_title) { var _self = this; var url = 'product-detail/'; url += product_id + '-'; url += _self.titleUrl(product_title); _self.locationUrl(url, ''); }, locationUrl: function(url) { if (url != "") { $location.url(url).replace(); } } } return data; }; $scope.getUrlProductDetail = function(str_in) { var str_out = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return str_out; }; $scope.getProductDetail = function(dataProductId_in) { console.log('getProductDetail : dataProductId_in : ', $scope.dataProductId_in); $scope.dataProductId = JSON.parse(dataProductId_in); }; $scope.$watch('productdata', function(newValue, oldValue) { if (newValue) { $scope.getProductDetail($scope.productdata); } else { return; } }); }; return promise; }); _ui_share_app.directive('componentProductCollection', function ($rootScope, $routeParams) { var templateName = 'componentProductCollection'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', _component: '@component', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.collection_id !== 'undefined'){ test = parseInt($routeParams.collection_id); a = $routeParams.collection_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; $scope.collectionArray = []; $scope.getData = function(){ var d = { 'txt_collection_id': $scope._getPostIdFromURL(), }; GAEAPI.get('collection/id',d,$scope).then(function(e){ if(e.ok==1){ $scope.collectionArray = e.data; } }); }; $scope.getData(); }; return promise; }); _ui_share_app.factory('$componentProductDetail', function componentProductDetail($routeParams,$timeout) { return { _key:'', key: function(){ return Math.floor((Math.random() * 9999) + 1000); }, viewRouteParams: function(){ return $routeParams; }, slick: function(){ var el = '[data-key="'+this._key+'"]'; return { left: function(){ return $timeout(function () { $(el).slick('slickPrev'); }, 100); }, right: function(){ return $timeout(function () { $(el).slick('slickNext'); }, 100); }, }; }, _private_data: [], get: function(call, params, callback){ if(!this._private_data.length){ GAEAPI.get(call, params).then(function(e){ this._private_data = e; callback(e); }); } else { return this._private_data; } } }; }); _ui_share_app.directive('productDetailPageA', function ($rootScope, $routeParams) { var templateName = 'productDetailPageA'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', datafonthover : '@datafonthover', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window,$http) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope._data_font_hover = (typeof $scope.datafonthover !== 'undefined' && typeof $scope.datafonthover !== '') ? $scope.datafonthover : 'primary_text'; $scope.data = false; $scope.dataPreserve = false; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; if(CUR_THEME.data.shop_id == "395"){ var req = { url:"https://gaedemo101.getappeasy.com/store/api/v1/product/id?txt_product_id="+$scope._getPostIdFromURL(), method: "GET", }; $http(req).then(function(res){ if(res.data.ok == 1){ var e = res.data; $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope.id); } }); } else { GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.getRelation($scope.data.product_referral[0].referral_id); $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope.id); } }); } $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 6, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; /* Change Big Image when click thumbnail */ $scope.changeBigImage=function(dataObject){ $timeout(function(){ var e = $('.gallery-display'); var el = $('.gallery-display').find('img').eq(0); e.css('opacity','0'); $timeout(function(){ el.attr('original-src',el.attr('src')); el.attr('src',dataObject.image_url); el.addClass('has-changed'); e.css('opacity','1'); }, 600); }, 300); }; /* Check If seo */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.hideCustom = function(){ if(CUR_THEME.shop_id()){ return true; } return false; }; $scope.checkHideCategory = function(){ if(CUR_THEME.shop_id()==598){ return true; } return false; }; $scope.qty_current=1; }; return promise; }); _ui_share_app.directive('productDetailPageB', function ($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageB'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', id:'@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.parentFactory = $componentProductDetail; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = $componentProductDetail.key(); $componentProductDetail._key =$scope._uniqueKey; return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.data = false; $scope.dataPreserve = false; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; /* Get data by product id */ /*$scope.buildDataProductRelate($scope.id);*/ /*GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); } });*/ $componentProductDetail.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}, function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); } }); $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; /* Check If seo */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope._makeProductToCarousel = function () { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { return $componentProductDetail.slick().left(); }; $scope._slickGoRight = function () { return $componentProductDetail.slick().right(); }; $rootScope.$on('repeatend', function() { if($('[data-key="'+$scope._uniqueKey+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); /* QTY */ $scope.qty_original=1; $scope.qty_current=1; $scope.qty_down=function(){ var a = $scope.qty_current; if(a <= 1){ $scope.qty_current = 1; return; } $scope.qty_current = (a - 1); }; $scope.qty_up=function(){ var a = $scope.qty_current; $scope.qty_current = (a + 1); }; }; return promise; }); _ui_share_app.directive('productDetailPageC', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageC'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', headerheight:'@headerheight', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; /* JQ: Scroll event */ angular.element($window).bind('scroll',function(){ if(!$scope.data){ return; } var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos", curPos, properHeight); if(curPos > properHeight){ angular.element('.block-background .bottom-info').addClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Slider Send */ $scope.data = false; $scope.dataPreserve = false; /* Get product id from url or from component */ $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; /* Get data by product id */ GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope._getPostIdFromURL()); } }); $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function () { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('[data-key="'+$scope._uniqueKey+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original=1; $scope.qty_current=1; }; return promise; }); _ui_share_app.directive('productDetailPageD', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageD'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id:'@id', headerheight:'@headerheight', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; angular.element($window).bind('scroll',function(){ var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos",curPos, properHeight); if(curPos > properHeight){ angular.element('.block-background .bottom-info').addClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* Get product id from url or from component */ $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; $scope.data = false; $scope.dataPreserve = false; /* Get data by product id */ GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); /*$scope.buildDataProductRelate($scope._getPostIdFromURL());*/ } }); $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; /*$scope.makeVariantsClick();*/ $scope.makeVaraintsClick_Normal(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.onClickVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; /* Select FIrst Varaint (SELECT) */ $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; /* Select FIrst Varaint (Normal click) */ $scope.makeVaraintsClick_Normal = function(){ $timeout(function(){ $('div.variantSelector').each(function(idx,obj){ $(this).find('span[data-index="'+idx+'"]').eq(0).click(); }); },2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function () { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('[data-key="'+$scope._uniqueKey+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original=1; $scope.qty_current=1; $scope.getShopName = function(){ return (typeof tttt !== 'undefined') ? tttt.shop_name : ''; }; }; return promise; }); _ui_share_app.directive('productDetailPageDa', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageDa'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id:'@id', headerheight:'@headerheight', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; angular.element($window).bind('scroll',function(){ var curPos = ($(document).scrollTop()); /* var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); */ var properHeight = $('.block-left').height(); console.debug("Cur pos",curPos, properHeight); console.log("Cur pos",curPos, properHeight); /* if($(window).width() > 991){ */ if ((curPos + ($(window).height() - 377)) > properHeight) { /* 114 before */ if ((properHeight - curPos) <= ($(window).height() - 377)) { if(properHeight - ($(window).height() - 377) < 0){ $('.set_height_fix').css('top','0px'); $('.set_height_fix').css('margin-bottom','0px'); }else{ $('.set_height_fix').css('top',(properHeight - ($(window).height() - 377)) + 'px'); $('.set_height_fix').css('margin-bottom',(properHeight - ($(window).height() - 377)) + 'px'); } } else { $('.set_height_fix').css('top','auto'); } angular.element('.set_height_fix').addClass('unactive'); /* angular.element('.block_bottom').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } */ } else { $('.set_height_fix').css('top','auto'); angular.element('.set_height_fix').removeClass('unactive'); /* angular.element('.block_bottom').removeClass('unactive'); */ } var properHeightAll = $('.block-background').height(); // var check_he = $('.block-background').height(); console.log("Cur pos-1",curPos, properHeightAll,properHeight,$(window).height()); if(properHeightAll > 903){ if ((curPos + ($(window).height() - 312)) >= properHeightAll) { /* 380 */ angular.element('.block_bottom').addClass('unactive'); } else { angular.element('.block_bottom').removeClass('unactive'); } } if(properHeightAll < properHeight){ if ((curPos + ($(window).height() - 380)) >= properHeight) { /* 380 */ angular.element('.block_bottom').addClass('unactive'); } else { angular.element('.block_bottom').removeClass('unactive'); } }else{ if ((curPos + ($(window).height() - 312)) >= properHeightAll) { /* 380 */ angular.element('.block_bottom').addClass('unactive'); } else { angular.element('.block_bottom').removeClass('unactive'); } } // if(properHeightAll > 903){ // else{ // if ((curPos + ($(window).height() - 380)) >= properHeight) { /* 380 */ // angular.element('.block_bottom').addClass('unactive'); // } else { // angular.element('.block_bottom').removeClass('unactive'); // } // } // }else{ // angular.element('.set_height_fix').removeClass('unactive'); // angular.element('.block_bottom').removeClass('unactive'); // } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; $scope.support_data = { category: [], }; $scope._getSupportDataCategory = function(type,data){ var dataSend = { 'txt_referral_id': data.product_referral_display.category[0].referral_id }; GAEAPI.get('referral/relation',dataSend , $scope).then(function(e){ if(e.ok == 1){ $scope.support_data.category = e.data; } }); }; /* Get product id from url or from component */ $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; $scope.data = false; $scope.dataPreserve = false; $scope.product_load = false; $scope._data_qty_model = 1; /* Get data by product id */ GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}, $scope).then(function(e){ if(e.ok == 1){ $scope.product_load = true; $scope.data = e.data; $scope.dataPreserve = e.data; $scope._getSupportDataCategory('category', e.data); if(e.data.product_tags.length > 0){ $scope.tags_product = e.data.product_tags.split(","); $scope.buildDataProductRelate(e.data.product_tags); } if(e.data.product_attribute.option_data != 0 && e.data.product_total_variant > 0){ if (e.data.product_attribute.option_data.variant_array.length != 0 && e.data.product_total_variant > 0) { var set_varia0 = e.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < e.data.product_attribute.option_data.variant_array.length; i++) { if(parseInt(set_varia0) >= parseInt(e.data.product_attribute.option_data.variant_array[i].price)){ set_varia0 = e.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = e.data.product_attribute.option_data.variant_array[i]; $scope.data.product_price = $scope.data_min.price; $scope.data.product_compare_price = $scope.data_min.compare_price; } } if($scope.data_min.length == 0){ $scope.data_min = e.data.product_attribute.option_data.variant_array[0]; $scope.data.product_price = $scope.data_min.price; $scope.data.product_compare_price = $scope.data_min.compare_price; } console.log("iujdishjdskd : ",$scope.data_min); /* $scope.buildVariantOption(e.data); $scope.buildMultipleQuantity(e.data); */ $scope.buildVariantOption(e.data); } } if(e.data.product_total_variant == 0 && e.data.product_total_stock > 0){ $scope.names = []; for (var i = 0; i < parseInt(e.data.product_total_stock); i++) { $scope.names.push(i+1); } console.log("nnames stock :",$scope.names); } if(e.data.product_total_variant == 0 && e.data.product_total_stock < 0){ $scope.names = []; for (var i = 0; i < 20; i++) { $scope.names.push(i+1); } console.log("nnames stock :",$scope.names); } if(e.data.product_total_variant > 0){ $scope.names = []; for (var i = 0; i < 20; i++) { $scope.names.push(i+1); } } /*$scope.buildDataProductRelate($scope._getPostIdFromURL());*/ } }); $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope._data_qty_selected = 1; $scope._data_qty_model1 = 1; $scope.watchQty = function(variant_key) { var e = angular.element('select[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('select[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt($('#detail_qty[variant-key="' + variant_key + '"]').val().substr(7)); console.log("data_set array test : ",i); $scope._data_qty_selected = i; $scope._data_qty_model = i; $scope._data_qty_model1 = i; // parseInt(e.val()); // alert(i); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.watchQty2 = function(variant_key) { var e = angular.element('select[name="detail_qty2"]'); if (typeof variant_key !== 'undefined') { e = angular.element('select[name="detail_qty2"][variant-key="' + variant_key + '"]'); } var i = parseInt($('#detail_qty2[variant-key="' + variant_key + '"]').val().substr(7)); console.log("data_set array test2 : ",i); $scope._data_qty_selected = i; $scope._data_qty_model = i; $scope._data_qty_model1 = i; // parseInt(e.val()); // alert(i); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d, $scope).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; /*$scope.makeVariantsClick();*/ $scope.makeVaraintsClick_Normal(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ $scope.testyuyu = 0; if (option_id == '') { $scope.ifOptionUnSelect = false; $scope.testyuyu = 0; // $('.d_qty_price').removeClass("active"); // $('.d_qty_price').removeClass("inin"); // $('.d_qty').removeClass('active').removeClass('inin'); // $('.dsetting').addClass("active"); // $('.d_qty_not_result').addClass("active"); $scope.dataVariantsPick[$index] = option_id; console.log("check_vareian 1000:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length); return GAEAPI.get('product/id', { 'txt_product_id': $scope._getPostIdFromURL() }, $scope).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; if (e.data.product_attribute.option_data != 0 && e.data.product_total_variant > 0) { if (e.data.product_attribute.option_data.variant_array.length != 0 && e.data.product_total_variant > 0) { var set_varia0 = e.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < e.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(e.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = e.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = e.data.product_attribute.option_data.variant_array[i]; // $scope.data = $scope.data_min[0]; $scope.data.product_price = $scope.data_min.price; $scope.data.product_compare_price = $scope.data_min.compare_price; } } if ($scope.data_min.length == 0) { $scope.data_min = e.data.product_attribute.option_data.variant_array[0]; $scope.data.product_price = $scope.data_min.price; } console.log("iujdishjdskd : ", $scope.data_min.price); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); } } } }); } else { $scope.dataVariantsPick[$index] = option_id; for (var i = 0; i < $scope.dataVariantsPick.length; i++) { if ($scope.dataVariantsPick[i] != undefined && $scope.dataVariantsPick[i] != "") { $scope.testyuyu++; } } if ($scope.testyuyu >= $scope.dataOption.length) { $scope.testyuyu = 0; $scope.ifOptionUnSelect = true; // $('.d_qty_not_result').removeClass("active"); // $('.dsetting').removeClass("active"); $scope.findVariantsData($scope.dataVariantsPick); } else { $scope.testyuyu = 0; // $('.d_qty').removeClass('active').removeClass('inin'); // $('.d_qty_price').removeClass("active"); // $('.d_qty_price').removeClass("inin"); } console.log("check_vareian 1001:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length, $scope.electric); } // console.log("onSelectVariantItems:", $index, option_id); // $scope.dataVariantsPick[$index] = option_id; // if($scope.dataVariantsPick.length >= $scope.dataOption.length){ // $scope.findVariantsData($scope.dataVariantsPick); // } }; $scope.onClickVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.names = []; $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; $scope.data.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; for (var i = 0; i < parseInt($scope.data.product_total_stock); i++) { $scope.names.push(i+1); } break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count); // $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = 0; $scope.data.product_compare_price = 0; } } }; /* Select FIrst Varaint (SELECT) */ $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; /* Select FIrst Varaint (Normal click) */ $scope.makeVaraintsClick_Normal = function(){ $timeout(function(){ $('div.variantSelector').each(function(idx,obj){ $(this).find('span[data-index="'+idx+'"]').eq(0).click(); }); },2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function () { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('[data-key="'+$scope._uniqueKey+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); $scope.tabView = 1; $scope.settabView = function(index){ $scope.tabView = index; }; $scope.qty_original=1; $scope.qty_current=1; $scope.ifOptionUnSelect = false; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; }; $scope.outofstock = 0; $scope.getOutofstock = function() { $scope.outofstock = 1; }; $scope.getShopName = function(){ return (typeof tttt !== 'undefined') ? tttt.shop_name : ''; }; }; return promise; }); _ui_share_app.directive('productDetailPageE', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageE'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; /* JQ: Scroll event */ angular.element($window).bind('scroll',function(){ if(!$scope.data){ return; } var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos", curPos, properHeight); if(curPos > properHeight){ angular.element('.block-background .bottom-info').addClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Slider Send */ $scope.data = false; $scope.dataPreserve = false; /* Get product id from url or from component */ $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; /* Get data by product id */ GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); /*$scope.buildDataProductRelate($scope._getPostIdFromURL());*/ } }); $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function () { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('[data-key="'+$scope._uniqueKey+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original=1; $scope.qty_current=1; $scope.viewImg = 0; $scope.changeImg = function(i){ return $scope.viewImg = i; }; }; return promise; }); _ui_share_app.directive('productDetailPageEa', function($rootScope, $routeParams, sliderProvider, $location) { var templateName = 'productDetailPageEa'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', buycol: '@buycol', buyicon: '@buyicon', buytext: '@buytext', language: '@language', btnstyle: '@btnstyle', maxstock: '@maxstock', videotext: '@videotext', description: '@description', info: '@info', specification: '@specification', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._component = "productDetailPageEa"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._buycol = ($scope.buycol != undefined && $scope.buycol != "") ? parseInt($scope.buycol) : 15; $scope._maxstock = ($scope.maxstock != undefined && $scope.maxstock != "") ? parseInt($scope.maxstock) : 20; $scope._btnstyle = ($scope.btnstyle != undefined && $scope.btnstyle != "") ? $scope.btnstyle : "filled_button_large"; $scope._buyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope.buyicon : "icnt_outline_cart01_dark.png"; $scope._buytext = ($scope.buytext != undefined && $scope.buytext != "") ? $scope.buytext : "เพิ่มในรถเข็น"; $scope._videotext = ($scope.videotext != undefined && $scope.videotext != "") ? $scope.videotext : "Video"; $scope._icebuyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope._icnPath + $scope.buyicon : $scope._icnPath + "icnt_outline_cart01_dark.png"; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getNamePage: function(arr) { var str = []; for (var i = 0; i < arr.length; i++) { if (i != 0) { str.push(arr[i]); } } return str.join(" "); }, getDataPage: function(params, callback) { var _self = this; var res_back_page = (params.back_page != undefined) ? params.back_page : ""; var res_data_id = (params.data_page != undefined) ? params.data_page.split("-", 1).join("") : ""; var res_data_name = (params.back_page != undefined) ? _self.getNamePage(params.data_page.split("-")) : ""; callback(res_back_page, res_data_id, res_data_name); }, getProductId: function(params, callback) { var _self = this; var product_id = (params.product_id != undefined) ? params.product_id.split("-", 1).join("") : false; _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getReferralId: function(productReferralDisplay, callback) { var _self = this; var referral_id = 0; if (productReferralDisplay.length != 0) { if (productReferralDisplay.category != undefined) { if (productReferralDisplay.category.length != 0) { referral_id = productReferralDisplay.category[0].referral_id } } } callback(referral_id); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carousel: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ fade: true, dots: false, arrows: false, infinite: true, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselDots: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: true, arrows: true, infinite: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselBar: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: false, arrows: false, infinite: false, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 6, slidesToScroll: 6, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 5, slidesToScroll: 5, } }, { breakpoint: 991, settings: { slidesToShow: 4, slidesToScroll: 4, } }, { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 3, } }] }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, slickCarousel: function(carousel, index) { var _self = this; $scope.setCarousel.index = index; setTimeout(function() { $('[data-key="' + carousel + '"]').slick('slickGoTo', index); }, 100); }, prevIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != 0) ? image_index - 1 : image - 1; _self.consoleLog("prevIndex index", $scope.setCarousel.index); }, nextIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != (image - 1)) ? image_index + 1 : 0; _self.consoleLog("nextIndex index", $scope.setCarousel.index); } } return getFunction; }; $scope.getAttribute = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, productAttribute: function(productAttribute, callback) { var _self = this; var attribute = { option_name: "", option_attribute: [] }; if (productAttribute.option_data != undefined) { if (productAttribute.option_data.variant_array != undefined && productAttribute.option_data.variant_array.length != 0) { for (var a = 0; a < productAttribute.option_data.pclass_array.length; a++) { attribute.option_name = attribute.option_name.concat(productAttribute.option_data.pclass_array[a].pclass_name, " "); } for (var b = 0; b < productAttribute.option_data.variant_array.length; b++) { var product_attribute = { product_id: productAttribute.option_data.variant_array[b].product_id, product_sku: productAttribute.option_data.variant_array[b].sku, product_title: "", product_price: parseFloat(productAttribute.option_data.variant_array[b].price), product_compare_price: parseFloat(productAttribute.option_data.variant_array[b].compare_price), product_total_stock: parseFloat(productAttribute.option_data.variant_array[b].total_stock), product_image: productAttribute.option_data.variant_array[b].variant_image } for (var c = 0; c < productAttribute.option_data.variant_array[b].option_name_array.length; c++) { product_attribute.product_title = product_attribute.product_title.concat(productAttribute.option_data.variant_array[b].option_name_array[c], " "); } attribute.option_attribute.push(product_attribute); } } } _self.consoleLog("productAttribute attribute ", attribute); callback(attribute); }, checkDiscountPrice: function(productDiscount, resPrice, resComparePrice, callback) { var _self = this; var price = 0; var compare_price = 0; if (productDiscount.length == 0) { price = parseFloat(resPrice); compare_price = parseFloat(resComparePrice); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(resPrice) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(resPrice); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(resPrice) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(resPrice); } } callback(price, compare_price); }, checkMinPrice: function(option, callback) { var _self = this; var price_min = parseFloat(option.option_attribute[0].product_price); var compare_price_min = parseFloat(option.option_attribute[0].product_compare_price); var total_stock = parseFloat(option.option_attribute[0].product_total_stock); for (var a = 0; a < option.option_attribute.length; a++) { if (price_min >= parseFloat(option.option_attribute[a].product_price)) { price_min = parseFloat(option.option_attribute[a].product_price); compare_price_min = parseFloat(option.option_attribute[a].product_compare_price); total_stock = parseFloat(option.option_attribute[a].product_total_stock); } } _self.consoleLog("checkPriceMin price_min ", price_min); _self.consoleLog("checkPriceMin compare_price_min ", compare_price_min); _self.consoleLog("checkPriceMin total_stock ", total_stock); callback(price_min, compare_price_min, total_stock); }, getTotalStock: function(totalStock, mixStock, callback) { var _self = this; var total_stock = (totalStock > 0) ? ((totalStock <= mixStock) ? totalStock : mixStock) : ((totalStock == -1) ? mixStock : totalStock); callback(total_stock); }, checkMinPrices: function(api, attribute, callback) { var _self = this; var dataPrice = { product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 } } if (attribute.option_attribute.length == 0) { _self.checkDiscountPrice(api.data.product_discount, api.data.product_price, api.data.product_compare_price, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(api.data.product_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, false); }); }); }); }); }); } else { _self.checkMinPrice(attribute, function(res_price_min, res_compare_price_min, res_total_stock) { _self.checkDiscountPrice(api.data.product_discount, res_price_min, res_compare_price_min, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(res_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, true); }); }); }); }); }); }); } }, priceIncludes: function(price, includes, callback) { var _self = this; var priceToString = (price == null) ? 0 : price; _self.consoleLog('priceIncludes priceToString : ', priceToString); callback(priceToString.toString().includes(includes)); }, checkPrice: function(price, callback) { var _self = this; _self.priceIncludes(price, '.', function(res) { _self.consoleLog("checkPrice res ", res); callback((!res) ? 0 : 2); }); }, onSelectOption: function(productId) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = productId; _self.consoleLog("onSelectOption productId ", productId); $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); for (var a = 0; a < $scope.data.attribute.dataArray.option_attribute.length; a++) { _self.consoleLog("onSelectOption option_attribute ", $scope.data.attribute.dataArray.option_attribute[a]); if ($scope.data.attribute.dataArray.option_attribute[a].product_id == productId) { if ($scope.data.attribute.dataArray.option_attribute[a].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var b = 0; b < $scope.dataApi.product.dataArray.product_image.length; b++) { if ($scope.dataApi.product.dataArray.product_image[b].image_id == $scope.data.attribute.dataArray.option_attribute[a].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, b); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[a].product_price, $scope.data.attribute.dataArray.option_attribute[a].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[a].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); break; } } }, onClickOption: function(index) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.data.attribute.productId = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); if ($scope.data.attribute.dataArray.option_attribute[index].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataApi.product.dataArray.product_image.length; i++) { if ($scope.dataApi.product.dataArray.product_image[i].image_id == $scope.data.attribute.dataArray.option_attribute[index].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, i); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[index].product_price, $scope.data.attribute.dataArray.option_attribute[index].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[index].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); } } return getFunction; }; $scope.getAttributeCustom = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, createArray: function(productCustomTemplates, callback) { var _self = this; var custom_attributes = []; if (productCustomTemplates.templates.length != 0) { if (productCustomTemplates.templates[0].option_sets.length != 0) { _self.getAttributes(productCustomTemplates.templates[0].option_sets, function(res_attributes) { custom_attributes = res_attributes; }); } } _self.consoleLog("createArray : productCustomTemplates", productCustomTemplates); _self.consoleLog("createArray : custom_attributes", custom_attributes); callback(custom_attributes, true); }, formatAttribute: function(index, optionSubsetIndex, setType, optionSetArray, callback) { var _self = this; var set_id = (setType == 'attribute') ? optionSetArray.set_id : optionSetArray.subset_id; var attribute = { attribute_index: index, attribute_option_subset_index: optionSubsetIndex, active_option_id: (optionSetArray.option_data.select_id != 0) ? optionSetArray.option_data.select_id : "-1", active_option_index: -1, active_option_index_str: "-1", active_textarea: "", active_array: [], set_id: set_id, name: optionSetArray.name, set_type: optionSetArray.ss_type, option: [] } callback(attribute); }, getOption: function(index, optionDataArray, callback) { var _self = this; var options = { index: index, ss_data_id: optionDataArray.ss_data_id, name: optionDataArray.name, image: optionDataArray.image, price: optionDataArray.price, compare_price: 0, total_stock: 0 } callback(options); }, getActive: function(index, activeOptionId, activeOptionIdIn, optionDataArray, callback) { var _self = this; var actives_index = (optionDataArray.ss_data_id == activeOptionId) ? index : activeOptionIdIn; var actives = (optionDataArray.ss_data_id != activeOptionId) ? "0" : "1"; callback(actives_index, actives); }, getAttributes: function(optionSetArray, callback) { var _self = this; var attributes = []; for (var index = 0; index < optionSetArray.length; index++) { _self.formatAttribute(index, 0, 'attribute', optionSetArray[index], function(res_attribute) { if (optionSetArray[index].option_subsets.length != 0) { for (var option_subset_index = 0; option_subset_index < optionSetArray[index].option_subsets.length; option_subset_index++) { _self.formatAttribute(index, option_subset_index, res_attribute.set_type, optionSetArray[index].option_subsets[option_subset_index], function(res_attribute_sub) { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_subsets[option_subset_index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute_sub.active_option_id, active_option_id, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute_sub.option = options; res_attribute_sub.active_option_index = active_option_id; res_attribute_sub.active_option_index_str = String(active_option_id); res_attribute_sub.active_array = active_option_array; attributes.push(res_attribute_sub); }); } } else { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute.active_option_id, active_option_id, optionSetArray[index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute.option = options; res_attribute.active_option_index = active_option_id; res_attribute.active_option_index_str = String(active_option_id); res_attribute.active_array = active_option_array; attributes.push(res_attribute); } }); } callback(attributes) }, getformatQuantity: function(index, attributeCustom, callback) { var _self = this; var quantity = { name: String(index + 1), dataArray: attributeCustom } callback(quantity); }, onClickRadio: function(index, index_option) { var _self = this; _self.consoleLog("onClickRadio : index", index); _self.consoleLog("onClickRadio : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickRadio : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickDropdown: function(index, index_option) { var _self = this; _self.consoleLog("onClickDropdown : index", index); _self.consoleLog("onClickDropdown : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickDropdown : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickCheckbox: function(index, index_option) { var _self = this; _self.consoleLog("onClickCheckbox : index", index); _self.consoleLog("onClickCheckbox : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i == parseInt(index_option)) ? (($scope.data.attribute_custom.dataArray[index].active_array[i] != "0") ? "0" : "1") : $scope.data.attribute_custom.dataArray[index].active_array[i]; } _self.consoleLog("onClickCheckbox : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); } } return getFunction; }; $scope.getReward = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, momentUnix: function(callback) { var _self = this; var now = moment().unix(); callback(now); }, getCalculator: function(sumProductPrice, reward, callback) { var _self = this; _self.consoleLog("getCalculator : sumProductPrice", sumProductPrice); _self.consoleLog("getCalculator : reward", reward); var point_reward = 0; if (reward.type_id == "100") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } else if (reward.type_id == "101") { point_reward = reward.reward_amount; } else if (reward.type_id == "102") { point_reward = (reward.reward_percent * sumProductPrice.price) / 100; } else if (reward.type_id == "103") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } _self.consoleLog("getCalculator : point_reward", point_reward); callback(point_reward); }, getProductReward: function(now, productReward, callback) { var _self = this; var reward = { reward_length: (productReward.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(productReward.reward_lifetime.lifetime_start_time); reward.lifetime_end_time = parseInt(productReward.reward_lifetime.lifetime_end_time); reward.type_id = productReward.reward_type_id; reward.amount = parseInt(productReward.reward_amount); reward.percent = parseInt(productReward.reward_percent); reward.every_price = parseInt(productReward.reward_every_price); } _self.consoleLog("getProductReward : reward", reward); callback(reward); }, getPointConfig: function(now, shopPointConfig, callback) { var _self = this; var reward = { reward_length: (shopPointConfig.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(shopPointConfig.er_from); reward.lifetime_end_time = parseInt(shopPointConfig.er_to); reward.type_id = "100"; reward.amount = parseInt(shopPointConfig.er_earn); reward.every_price = parseInt(shopPointConfig.er_rate); } _self.consoleLog("getPointConfig : reward", reward); callback(reward); }, checkPointReward: function(reward, callback) { var _self = this; var state = false; if (reward.reward_length) { var start = reward.lifetime_start_time < reward.lifetime_time && reward.lifetime_start_time != 0; var end = (reward.lifetime_end_time != -1) ? reward.lifetime_time <= reward.lifetime_end_time && reward.lifetime_end_time != 0 : true; if (start && end) { if (reward.type_id == "100") { var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } else if (reward.type_id == "101") { var amount = reward.amount != 0; if (amount) { state = true; } } else if (reward.type_id == "102") { var percent = reward.percent != 0; if (percent) { state = true; } } else if (reward.type_id == "103") { var percent = reward.percent != 0; var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } } } callback(state); }, checkReward: function(rewardProduct, rewardPointConfig, callback) { var _self = this; _self.consoleLog("checkReward : rewardProduct", rewardProduct); _self.consoleLog("checkReward : rewardPointConfig", rewardPointConfig); var reward = { type_id: "0", amount: 0, percent: 0, every_price: 0 }; _self.checkPointReward(rewardProduct, function(res_state_product) { _self.checkPointReward(rewardPointConfig, function(res_state_point_config) { if (res_state_point_config) { reward.type_id = rewardPointConfig.type_id; reward.type_id = rewardPointConfig.type_id; reward.amount = rewardPointConfig.amount; reward.percent = rewardPointConfig.percent; reward.every_price = rewardPointConfig.every_price; } else if (res_state_product) { reward.type_id = rewardProduct.type_id; reward.amount = rewardProduct.amount; reward.percent = rewardProduct.percent; reward.every_price = rewardProduct.every_price; } _self.consoleLog("checkReward : reward", reward); callback(reward); }); }); }, checkRewardType: function(productReward, shopPointConfig, callback) { var _self = this; _self.momentUnix(function(now) { _self.getProductReward(now, productReward, function(res_reward_product) { _self.getPointConfig(now, shopPointConfig, function(res_reward_point_config) { _self.checkReward(res_reward_product, res_reward_point_config, function(res_reward) { callback(res_reward); }); }); }); }); }, createReward: function(productReward, shopPointConfig, callback) { var _self = this; _self.consoleLog("createReward : productReward", productReward); _self.consoleLog("createReward : shopPointConfig", shopPointConfig); _self.checkRewardType(productReward, shopPointConfig, function(res_reward) { _self.consoleLog("createReward : res_reward", res_reward); callback(res_reward); }); } } return getFunction; }; $scope.getQuantity = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, upDateReward: function() { var _self = this; }, upDateReward: function() { var _self = this; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); }, upDatePrice: function() { var _self = this; var product_price = $scope.data.product_price.price * $scope.data.quantity.quantity_input; var product_compare_price = $scope.data.product_compare_price.price * $scope.data.quantity.quantity_input; $scope.getAttribute().checkPrice(product_price, function(res_price_ecimals) { $scope.data.sum_product_price.price = product_price; $scope.data.sum_product_price.price_ecimals = res_price_ecimals; $scope.getAttribute().checkPrice(product_compare_price, function(res_compare_price_ecimals) { $scope.data.sum_product_compare_price.price = product_compare_price; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((product_compare_price - product_price) > 0) ? product_compare_price - product_price : 0; $scope.getAttribute().checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.upDateReward(); }); }); }); }, input: function(quantityInput) { var _self = this; _self.consoleLog("input : quantityInput", quantityInput); quantityInput = (quantityInput == null) ? 1 : parseInt(quantityInput); _self.consoleLog("input : quantityInput", quantityInput); if (quantityInput != null) { if (quantityInput >= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_max; } if (quantityInput <= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } } else { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } _self.upDatePrice(); }, minus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input - 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_min", $scope.data.quantity.quantity_min); if (quantity >= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); }, plus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input + 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_max", $scope.data.quantity.quantity_max); if (quantity <= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); } } return getFunction; }; $scope.getBuy = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getProductId: function(params, callback) { var _self = this; var product_id = params.product_id.split("-", 1).join(""); _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, postApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.post(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, UiCartProductAdd: function(productId, quantityInput, promotionId, customOptions, callback) { UiCart.delegate.product.add(productId, quantityInput, promotionId, function(res_data) { callback(res_data); }); }, isProgress: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isProgress(productId)) ? true : false; _self.consoleLog("isProgress : productId", productId); _self.consoleLog("isProgress : state", state); callback(state); }, isSelected: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isSelected(productId)) ? true : false; _self.consoleLog("isSelected : productId", productId); _self.consoleLog("isSelected : state", state); callback(state); }, isSelectedReturn: function(productId) { var _self = this; var ui_cart_state = (UiCart.delegate.product.isSelected(productId)) ? true : false; if (!$scope.setBuy.state_active) { $scope.setBuy.state_active = true; var state_process = $scope.setBuy.state_process; var state_step = $scope.setBuy.state_step; if (ui_cart_state && !state_process && state_step != 4) /* cart */ { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else if (!ui_cart_state && !state_process && state_step != 0) /* unset */ { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } else { $scope.setBuy.state_active = false; } } return ui_cart_state; }, updateState: function(productId) { _self = this; _self.isSelected(productId, function(res_state) { if (res_state) { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } return res_state; }); }, uiCart: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; _self.UiCartProductAdd(productId, quantityInput, promotionId, customOptions, function(res_data) { if (res_data) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }, postApi: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; var custom_options = {}; var dataSend = { 'txt_product_id': productId, 'txt_amount': quantityInput, 'txt_is_clear_cart_before': "0", 'txt_custom_options_json': JSON.stringify(custom_options) }; _self.dataSend("cart/product_add", dataSend, function(res_api, res_dataSend) { _self.postApi(res_api, res_dataSend, function(res_ok, res_api, state) { if (res_ok) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }); }, onProcess: function(data, productId, quantityInput, promotionId, customOptions) { var _self = this; if (!$scope.setBuy.state_process) { $scope.setBuy.state_process = true; _self.isSelected(productId, function(res_state) { if (!res_state) { _self.onLoad($scope.setBuy.state_step, function(res_step) { if (data.sum_product_price.price != 0 && data.quantity.quantity_max != 0 && (data.attribute.state == (data.attribute.productId != ''))) { /* UiCart */ _self.uiCart(productId, quantityInput, promotionId, customOptions, res_step); /* api post offline */ /*_self.postApi(productId, quantityInput, promotionId, customOptions, res_step); */ } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); } else { $scope.setBuy.state_process = false; } }); } }, onTimeout: function(time, callback) { var _self = this; var load = $timeout(function() { $timeout.cancel(load); callback(true) }, time); }, onUnset: function(step, callback) { var _self = this; step = (step == 0) ? 0 : 0; $scope.setBuy.state_step = step; callback(step); }, onLoad: function(step, callback) { var _self = this; step = (step == 0 || step == 1) ? 1 : 0; $scope.setBuy.state_step = step; callback(step); }, onPass: function(step, callback) { var _self = this; step = (step == 1 || step == 2) ? 2 : 0; $scope.setBuy.state_step = step; callback(step); }, onError: function(step, callback) { var _self = this; step = (step == 1 || step == 3) ? 3 : 0; $scope.setBuy.state_step = step; callback(step); }, onCart: function(step, callback) { var _self = this; step = (step == 2 || step == 4) ? 4 : 0; $scope.setBuy.state_step = step; callback(step); }, main: function(callback) { var _self = this; } } return getFunction; }; $scope.getDetail = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getDetail: function(api, callback) { var _self = this; var description = api.product_description; var info = api.product_more_info; var specificatio = []; if (api.product_attribute.specification_data != undefined) { specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? api.product_attribute.specification_data.pclass_array : []; } var state_specificatio = false; if (api.product_attribute.specification_data != undefined) { state_specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? true : false; } var state_info = (api.product_is_more_info == 1) ? true : false; _self.consoleLog("getDetail : description", description); _self.consoleLog("getDetail : info", info); _self.consoleLog("getDetail : state_info", state_info); callback(description, info, state_info, specificatio, state_specificatio); }, onClickDetail: function(index) { var _self = this; $scope.data.detail.active = index; _self.consoleLog("onClickDetail : data.detail.active", $scope.data.detail.active); } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageName: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page_name); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.countDown = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getLocation: function(callback) { var _self = this; var res_location = $location; _self.consoleLog("getLocation", "res_location", res_location); callback(res_location); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; _self.consoleLog("getRouteParams", "params", params); callback(params); }, getLocationUrlNameProductDetail: function(callback) { var _self = this; _self.getRouteParams(function(res_params) { _self.getLocation(function(res_location) { var url_page_name = "/product-detail/" + res_params.product_id; var res_url_name_product_detail = (res_location.url() == url_page_name) ? true : false; _self.consoleLog("getLocationUrlNameProductDeal", "res_url_name_product_detail", res_url_name_product_detail); callback(res_url_name_product_detail); }); }); }, getUnix: function(callback) { var _self = this; var now = moment().unix(); _self.consoleLog("getUnix", "now", now); callback(now); }, getCountDown: function(now, product_lifetime, callback) { var _self = this; var countdown_unix = parseInt(product_lifetime.lifetime_end_time) - now; var milliseconds = moment.duration(countdown_unix * 1000, "milliseconds"); var res_countdown = ((milliseconds.days() <= 9) ? '0' + milliseconds.days() : milliseconds.days()); res_countdown = res_countdown + ' : ' + ((milliseconds.hours() <= 9) ? '0' + milliseconds.hours() : milliseconds.hours()); res_countdown = res_countdown + ' : ' + ((milliseconds.minutes() <= 9) ? '0' + milliseconds.minutes() : milliseconds.minutes()); res_countdown = res_countdown + ' : ' + ((milliseconds.seconds() <= 9) ? '0' + milliseconds.seconds() : milliseconds.seconds()); _self.consoleLog("getCountDown", "res_countdown", res_countdown); callback(res_countdown, countdown_unix); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page); }, countDownByProduct: function(now, data_array, callback) { var _self = this; if (data_array.length != 0) { if (data_array.product_lifetime.length != 0) { _self.getCountDown(now, data_array.product_lifetime, function(res_count_down, res_countdown_unix) { data_array.product_lifetime.lifetime_countdown = (res_countdown_unix > 0) ? res_count_down : ""; if (data_array.product_lifetime.lifetime_countdown == "") { _self.getNameUrl(data_array.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", data_array.product_set_array[0].product_id, res_name); }); } }); } } _self.consoleLog("countDownByProduct", "data_array", data_array); callback(data_array); }, loop: function() { var _self = this; var load = $timeout(function() { $timeout.cancel(load); _self.getUnix(function(res_now) { _self.countDownByProduct(res_now, $scope.dataApi.product.dataArray, function(data_array) { $scope.dataApi.product.dataArray = data_array; _self.getLocationUrlNameProductDetail(function(res_url_name_product_detail) { if (res_url_name_product_detail) { _self.loop(); } }); }); }); }, 1000); } } return getFunction; }; $scope.control = function() { var getFunction = { popupVideo: function(state, video_link, video_embed_code) { var _self = this; if (video_embed_code != '') { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } else if (video_link != '') { window.open(video_link, '_blank'); } else { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } }, main: function() { var _self = this; } } return getFunction; }; $scope.data_control = { page_video: { popup: false, shop_video_embed_code: "" } } $scope.countDown().loop(); /* set carousel */ $scope.setCarousel = { carousel: 0, index: 0 }; $scope.getCarousel().getCarousel($scope.setCarousel.carousel, function(res_carousel_id) { $scope.setCarousel.carousel = res_carousel_id; }); /* set carousel */ /* get product api */ $scope.dataApi = { reward: { dataSend: {}, api: "shop/current", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, product: { dataSend: { txt_product_id: 0 }, api: "product/id", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, relation: { dataSend: { txt_referral_id: 0 }, api: "referral/relation", ok: false, dataArray: [], dataArrayState: { load: false, done: false } } }; $scope.data = { resParams: "", back: { page_name: "", data_id: "", data_name: "" }, attribute: { state: false, productId: "", dataArray: [] }, attribute_custom: { state: false, dataArray: [] }, reward: { quantity_name: 'reward', type_id: "0", reward_amount: 0, reward_percent: 0, reward_every_price: 0, point_reward: 0 }, quantity: { quantity_name: 'quantity', quantity_min: 1, quantity_max: 1, quantity_input: 1, quantity_select: [] }, product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, detail: { active: '0', dataArray: [{ index: '0', state: true, en: ($scope.description != undefined && $scope.description != "") ? $scope.description : 'Description', th: '', data: '', dataArray: [] }, { index: '1', state: true, en: ($scope.info != undefined && $scope.info != "") ? $scope.info : 'Info', th: '', data: '', dataArray: [] }, { index: '2', state: true, en: ($scope.specification != undefined && $scope.specification != "") ? $scope.specification : 'Specification', th: '', data: '', dataArray: [] }] } }; $scope.setBuy = { state_active: false, state_process: false, state_step: 0, state_data_font_color: "", state_data_background_color: "", stepArray: [{ step: 0, name: "unset", icon: $scope._icebuyicon, state: "เพิ่มในรถเข็น", data_font_color: "", data_background_color: "" }, { step: 1, name: "load", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 2, name: "pass", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 3, name: "error", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 4, name: "cart", icon: "", state: "ดูรถเข็น", data_font_color: "", data_background_color: "primary_darkest" }] }; /* - get api product/id start - */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.data.resParams = res_params; $scope.getData().getDataPage(res_params, function(res_back_page, res_data_id, res_data_name) { $scope.data.back.page_name = res_back_page; $scope.data.back.data_id = res_data_id; $scope.data.back.data_name = res_data_name; }); $scope.dataApi.product.dataArrayState = res_state; $scope.getData().getProductId(res_params, function(res_product_id) { $scope.dataApi.product.dataSend.txt_product_id = (res_product_id != false) ? res_product_id : 0; $scope.getData().dataSend($scope.dataApi.product.api, $scope.dataApi.product.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_product, res_state) { $scope.dataApi.product.ok = res_ok; $scope.dataApi.product.dataArray = get_res_api_product.data; $scope.getData().consoleLog("get_res_api_product", get_res_api_product); $scope.dataApi.product.dataArrayState = res_state; /* -- get api shop/current to reward -- */ if (res_ok) { $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.reward.dataArrayState = res_state; $scope.getData().dataSend($scope.dataApi.reward.api, $scope.dataApi.reward.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_shop, res_state) { $scope.dataApi.reward.ok = res_ok; $scope.dataApi.reward.dataArray = get_res_api_shop.data; $scope.dataApi.reward.dataArrayState = res_state; $scope.getReward().createReward($scope.dataApi.product.dataArray.product_reward, get_res_api_shop.data.shop_point_config, function(res_reward) { $scope.data.reward.type_id = res_reward.type_id; $scope.data.reward.reward_amount = res_reward.amount; $scope.data.reward.reward_percent = res_reward.percent; $scope.data.reward.reward_every_price = res_reward.every_price; /* --- Wait product/id ,shop/current --- */ /* ---- get attribute ---- */ $scope.getAttribute().productAttribute(get_res_api_product.data.product_attribute, function(res_attribute) { $scope.data.attribute.dataArray = res_attribute; $scope.getAttribute().checkMinPrices(get_res_api_product, res_attribute, function(res_data_price, res_state) { $scope.data.attribute.state = res_state; $scope.data.product_price = res_data_price.product_price; $scope.data.product_compare_price = res_data_price.product_compare_price; $scope.data.sum_product_price = res_data_price.sum_product_price; $scope.data.sum_product_compare_price = res_data_price.sum_product_compare_price; $scope.data.sum_product_compare_minus_sum_product_price = res_data_price.sum_product_compare_minus_sum_product_price; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); /* ----- stock ----- */ $scope.data.quantity.quantity_max = res_data_price.product_price.total_stock; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_data_price.product_price.total_stock; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* ----- stock ----- */ }); }); /* ---- get attribute ---- */ /* ---- get attribute custom ---- */ $scope.getAttributeCustom().createArray(get_res_api_product.data.product_custom_templates, function(res_custom_attribute, res_state) { $scope.data.attribute_custom.state = res_state; $scope.data.attribute_custom.dataArray = res_custom_attribute; }); /* ---- get attribute custom ---- */ /* ---- get detail ---- */ $scope.getDetail().getDetail(get_res_api_product.data, function(res_description, res_info, res_state_info, res_specificatio, res_state_specificatio) { $scope.data.detail.dataArray[0].data = res_description; $scope.data.detail.dataArray[1].data = res_info; $scope.data.detail.dataArray[1].state = res_state_info; $scope.data.detail.dataArray[2].dataArray = res_specificatio; $scope.data.detail.dataArray[2].state = res_state_specificatio; }); /* ---- get detail ---- */ /* ---- update state ---- */ $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); /* ---- update state ---- */ /* --- Wait product/id ,shop/current --- */ }); }); }); }); /* -- get api shop/current to reward -- */ /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.relation.dataArrayState = res_state; $scope.getData().getReferralId(get_res_api_product.data.product_referral_display, function(res_referral_id) { $scope.dataApi.relation.dataSend.txt_referral_id = res_referral_id; $scope.getData().dataSend($scope.dataApi.relation.api, $scope.dataApi.relation.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_referral, res_state) { $scope.dataApi.relation.ok = res_ok; $scope.dataApi.relation.dataArray = get_res_api_referral.data; $scope.dataApi.relation.dataArrayState = res_state; }); }); }); }); /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ } else { /* ok = false */ if ($scope.dataApi.product.dataArray.length != 0) { /* product deal to product original */ if ($scope.dataApi.product.dataArray.product_set_array.length != 0) { $scope.countDown().getNameUrl($scope.dataApi.product.dataArray.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", $scope.dataApi.product.dataArray.product_set_array[0].product_id, res_name); }); } else { $scope.pages().pageName("home"); } } else { /* product null */ $scope.pages().pageName("home"); } } }); }); }); }); /* - get api product/id end - */ /* get product api */ }; return promise; });_ui_share_app.directive('productDetailPageEb', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageEb'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.checkPrice = function(price) { var check_price = 0; var _price = (price != undefined && price != "" && price != null) ? price.toString() : "0"; if (_price.includes(".")) { check_price = 2; } return check_price; }; $scope.dataTag = false; $scope._dataArray = []; $scope.product_id = ""; $scope.product_sku = ""; $scope.product_code = ""; $scope.product_price = 0; $scope.product_compare_price = 0; $scope.promotion_list = 0; $scope._dataArrayState = { load: true, done: false }; $scope.nowMoment = moment().unix(); console.log("promotion_list : ", $scope.promotion_list); $scope.dataShopCurrent = []; $scope.dataShopPointConfig = []; $scope.getShopCurrent = function() { var dataSend = {}; GAEAPI.get('shop/current', dataSend).then(function(output) { console.log("getShopCurrent : output : ", output); if (output.ok == 1) { $scope.dataShopCurrent = output.data; console.log("getShopCurrent : dataShopCurrent : ", $scope.dataShopCurrent); $scope.dataShopPointConfig = output.data.shop_point_config; console.log("getShopCurrent : dataShopPointConfig : ", $scope.dataShopPointConfig); } }); }; $scope.getShopCurrent(); $scope.getShopPointConfigRewardState = function(product_price, quantity) { var state = 'RewardShop'; var sup_price = product_price * quantity; if ($scope.dataShopPointConfig.length != 0) { if (parseInt($scope.dataShopPointConfig.er_rate) != 0 && parseInt($scope.dataShopPointConfig.er_earn) != 0) { if (parseInt($scope.dataShopPointConfig.er_rate) <= sup_price) { state = 'RewardShop'; return state; } else { state = 'High'; return state; } } else { return 'RewardProduct'; return state; } } else { return 'RewardProduct'; } }; $scope.getShopPointConfigReward = function(product_price, quantity) { var sup_price = 0; var er_rate = 0; var er_earn = 0; var mathFloor = 0; var point = 0; // console.log("getShopPointConfigReward : shop_point_config.er_rate : ",$scope.dataShopPointConfig.er_rate); if ($scope.dataShopPointConfig.length != 0) { sup_price = product_price * quantity; er_rate = parseInt($scope.dataShopPointConfig.er_rate); er_earn = parseInt($scope.dataShopPointConfig.er_earn); mathFloor = Math.floor(sup_price / er_rate); point = mathFloor * er_earn; return point; } else { return point; } } $scope._getReward = function(datain, product_price, qty) { if (datain.length == 0) { return 'Data Reward Error'; } console.log("_getReward : product_price : ", product_price, " qty : ", qty); var reward = "NULL"; if (datain.reward_type_id == "101") {} else if (datain.reward_type_id == "102") {} else if (datain.reward_type_id == "103") { var reward_every_price = parseInt(datain.reward_every_price); var sum_product_price = Math.round(product_price) * qty; var reward_amount = parseInt(datain.reward_amount); console.log("_getReward : reward_every_price : ", reward_every_price, " sum_product_price : ", sum_product_price, " reward_amount : ", reward_amount); if (reward_every_price <= sum_product_price) { var divided = Math.floor(sum_product_price / reward_every_price); var multiplied = divided * reward_amount; console.log("_getReward : divided : ", divided, " multiplied : ", multiplied); reward = multiplied; } else { reward = "ZERO"; } } else { return 'Data Reward Type Id Error'; } return reward; }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'txt_product_id': id, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; if ($scope._dataArray.product_is_promotion != 0) { if ($scope._dataArray.product_promotion) { $scope.promotion_list = $scope._dataArray.product_promotion[0].promotion_id; } } console.log("promotion_list : ", $scope.promotion_list); console.log("_getDataArray _dataArray : ", $scope._dataArray); $scope.product_id = $scope._dataArray.product_id; $scope.dataPreserve = res.data; if (res.data.product_sku != undefined) { $scope.product_sku = res.data.product_sku; } if (res.data.product_code != undefined) { $scope.product_code = res.data.product_code; } console.log("res.data.product_discount : ", res.data.product_discount); if (res.data.product_discount.length != 0) { $scope.product_price = $scope.calculate(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_lifetime.lifetime_start_time, res.data.product_discount.discount_lifetime.lifetime_end_time, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_lifetime.lifetime_start_time, res.data.product_discount.discount_lifetime.lifetime_end_time, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); } else { $scope.product_price = res.data.product_price; $scope.product_compare_price = res.data.product_compare_price; } if ($scope._dataArray.product_referral_display.category != 'undefined' && $scope._dataArray.product_referral_display.category != null) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.dataTag = res.data.product_tags.split(","); $scope.qtyCurrentSize(res.data.product_total_variant, res.data.product_total_stock); $scope.buildVariantOption(res.data); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.mkCarousel = function(elem) { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { slidesToShow: 1, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var dataSend = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.dataRelation = res.data; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getIdUrl = function() { var getData = []; var returnData = ''; if (typeof $routeParams.product_id !== 'undefined') { getData = $routeParams.product_id; returnData = getData.split("-"); return returnData[0]; } }; $scope._stateReward = function(datain) { var state = false; /* console.log("_stateReward : reward_lifetime : ", datain.reward_lifetime); */ if (datain.length != 0) { state = true; } return state; }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleStatres.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleStatres.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } // $scope.pricefull = function(price, compare_price, discount_id , lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { // var pricefull = 0; // if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= nowMoment)) { // if (price != undefined && price != 0) { // pricefull = price; // $scope._pricefullState.pricefull = 'not zero'; // } else { // pricefull = 0; // $scope._pricefullState.pricefull = 'zero'; // } // } else { // if (compare_price > 0 && compare_price != undefined) { // pricefull = compare_price; // $scope._pricefullState.pricefull = 'not zero'; // } else { // $scope._pricefullState.pricefull = 'zero'; // } // } // return pricefull; // } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { console.log("calculate : ", price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent); console.log("calculate : ", lifetime_start_time <= $scope.nowMoment); console.log("calculate : ", lifetime_end_time >= $scope.nowMoment); console.log("calculate : ", (lifetime_end_time == -1 || lifetime_end_time >= nowMoment)); var calculate = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } // $scope.calculate = function(price, compare_price, discount_id , lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { // var calculate = 0; // if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= nowMoment)) { // if (discount_price != 0 && discount_percent == 0) { // calculate = price - discount_price; // } else if (discount_percent != 0 && discount_price == 0) { // calculate = price - ((discount_percent / 100) * price); // } // } else { // calculate = price // } // if (calculate != undefined && calculate != 0) { // $scope._calculateState.calculate = 'not zero'; // } else { // $scope._calculateState.calculate = 'zero'; // } // return (calculate > 0) ? calculate : 0; // } $scope.qtyCurrentSize = function(product_total_variant, product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : product_total_variant : ", product_total_variant, "product_total_stock : ", product_total_stock); if (product_total_variant == 0) { if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; if (product_total_stock >= 50) { for (var i = 0; i < 50; i++) { $scope.qty_current_size.push(i + 1); } } else { for (var i = 0; i < parseInt(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_stock < 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < 50; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock == 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else { $scope.qty_current_size_state = false; $scope.buy_state = false; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_variant > 0) { if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < product_total_stock; i++) { $scope.qty_current_size.push(i + 1); } } } $scope.qtyShow($scope.qty_current_size); }; $scope.htmlSelectTime = 0; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } } $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").val() == undefined) { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); check_int = 1; } else if ($(".d_qty").val() == "? number:1 ?") { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); } else { check_int = parseInt($(".d_qty").val()); $(".d_qty").val(check_int); } return check_int; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems option_id:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems dataVariantsPick:", $scope.dataVariantsPick); if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); console.log("dataVariants :", dataVariants); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; if (dataVariants[i].sku != "") { $scope.product_sku = dataVariants[i].sku; } else { $scope.product_sku = $scope._dataArray.product_sku; } if (dataVariants[i].sku != "") { $scope.product_code = dataVariants[i].barcode; } else { $scope.product_code = $scope._dataArray.product_code; } console.log("$scope._dataArray.product_discount : ", $scope._dataArray.product_discount); $scope.product_price = $scope.calculate(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_lifetime.lifetime_start_time, $scope._dataArray.product_discount.discount_lifetime.lifetime_end_time, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_lifetime.lifetime_start_time, $scope._dataArray.product_discount.discount_lifetime.lifetime_end_time, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); break; } else { $scope.qty_current_size_state = false; $scope.buy_state = false; $scope.product_price = $scope._dataArray.product_price; $scope.product_compare_price = $scope._dataArray.product_compare_price; $scope.product_sku = $scope._dataArray.product_sku; $scope.product_code = $scope._dataArray.product_code; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope.viewInfo = 1; $scope.view = function(input) { $scope.viewInfo = input; } $scope._getDataArray($scope._getIdUrl()); // setTimeout(function() { // alert($('input[name=radiogroup]:checked').val()); // }, 700); $scope.clickckvalue = function() { var result = 0; $scope.promotion_list = $('input[name=radiogroup]:checked').val(); console.log("promotion_list : ", $scope.promotion_list); if ($('input[name=radiogroup]:checked').val() != "" && $('input[name=radiogroup]:checked').val() != undefined) { result = $('input[name=radiogroup]:checked').val(); } else { result = 0; } return result; } }; return promise; });_ui_share_app.directive('productDetailPageEc', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageEc'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataTag = false; $scope._dataArray = []; $scope.product_id = ""; $scope.product_sku = ""; $scope.product_code = ""; $scope.product_price = 0; $scope.product_compare_price = 0; $scope.promotion_list = 0; $scope._dataArrayState = { load: true, done: false }; console.log("promotion_list : ", $scope.promotion_list); $scope.dataShopCurrent = []; $scope.dataShopPointConfig = []; $scope.getShopCurrent = function() { var dataSend = {}; GAEAPI.get('shop/current', dataSend).then(function(output) { console.log("getShopCurrent : output : ", output); if (output.ok == 1) { $scope.dataShopCurrent = output.data; console.log("getShopCurrent : dataShopCurrent : ", $scope.dataShopCurrent); $scope.dataShopPointConfig = output.data.shop_point_config; console.log("getShopCurrent : dataShopPointConfig : ", $scope.dataShopPointConfig); } }); }; $scope.getShopCurrent(); $scope.getShopPointConfigRewardState = function(product_price, quantity) { var state = 'RewardShop'; var sup_price = product_price * quantity; if ($scope.dataShopPointConfig.length != 0) { if (parseFloat($scope.dataShopPointConfig.er_rate) != 0 && parseFloat($scope.dataShopPointConfig.er_earn) != 0) { if (parseFloat($scope.dataShopPointConfig.er_rate) <= sup_price) { state = 'RewardShop'; return state; } else { state = 'High'; return state; } } else { return 'RewardProduct'; return state; } } else { return 'RewardProduct'; } }; $scope.getShopPointConfigReward = function(product_price, quantity) { var sup_price = 0; var er_rate = 0; var er_earn = 0; var mathFloor = 0; var point = 0; // console.log("getShopPointConfigReward : shop_point_config.er_rate : ",$scope.dataShopPointConfig.er_rate); if ($scope.dataShopPointConfig.length != 0) { sup_price = product_price * quantity; er_rate = parseFloat($scope.dataShopPointConfig.er_rate); er_earn = parseFloat($scope.dataShopPointConfig.er_earn); mathFloor = Math.floor(sup_price / er_rate); point = mathFloor * er_earn; return point; } else { return point; } } $scope._getReward = function(datain, product_price, qty) { if (datain.length == 0) { return 'Data Reward Error'; } console.log("_getReward : product_price : ", product_price, " qty : ", qty); var reward = "NULL"; if (datain.reward_type_id == "101") {} else if (datain.reward_type_id == "102") {} else if (datain.reward_type_id == "103") { var reward_every_price = parseFloat(datain.reward_every_price); var sum_product_price = Math.round(product_price) * qty; var reward_amount = parseFloat(datain.reward_amount); console.log("_getReward : reward_every_price : ", reward_every_price, " sum_product_price : ", sum_product_price, " reward_amount : ", reward_amount); if (reward_every_price <= sum_product_price) { var divided = Math.floor(sum_product_price / reward_every_price); var multiplied = divided * reward_amount; console.log("_getReward : divided : ", divided, " multiplied : ", multiplied); reward = multiplied; } else { reward = "ZERO"; } } else { return 'Data Reward Type Id Error'; } return reward; }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'txt_product_id': id, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; // if ($scope._dataArray.product_is_promotion != 0) { // $scope.promotion_list = $scope._dataArray.product_promotion[0].promotion_id; // } console.log("promotion_list : ", $scope.promotion_list); console.log("_getDataArray _dataArray : ", $scope._dataArray); $scope.product_id = $scope._dataArray.product_id; $scope.dataPreserve = res.data; if (res.data.product_sku != undefined) { $scope.product_sku = res.data.product_sku; } if (res.data.product_code != undefined) { $scope.product_code = res.data.product_code; } $scope.product_price = $scope.calculate(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); if ($scope._dataArray.product_referral_display.category != 'undefined' && $scope._dataArray.product_referral_display.category != null) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.dataTag = res.data.product_tags.split(","); $scope.qtyCurrentSize(res.data.product_total_variant, res.data.product_total_stock); $scope.buildVariantOption(res.data); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.mkCarousel = function(elem) { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { slidesToShow: 1, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var dataSend = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.dataRelation = res.data; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getIdUrl = function() { var getData = []; var returnData = ''; if (typeof $routeParams.product_id !== 'undefined') { getData = $routeParams.product_id; returnData = getData.split("-"); return returnData[0]; } }; $scope._stateReward = function(datain) { var state = false; /* console.log("_stateReward : reward_lifetime : ", datain.reward_lifetime); */ if (datain.length != 0) { state = true; } return state; }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleStatres.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleStatres.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.qtyCurrentSize = function(product_total_variant, product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : product_total_variant : ", product_total_variant, "product_total_stock : ", product_total_stock); if (product_total_variant == 0) { if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; if (product_total_stock >= 20) { for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else { for (var i = 0; i < parseFloat(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_stock < 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock == 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else { $scope.qty_current_size_state = false; $scope.buy_state = false; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_variant > 0) { if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < product_total_stock; i++) { $scope.qty_current_size.push(i + 1); } } } $scope.qtyShow($scope.qty_current_size); }; $scope.htmlSelectTime = 0; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } } $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").val() == undefined) { $(".d_qty").val("1"); check_int = parseFloat($(".d_qty").val()); check_int = 1; } else if ($(".d_qty").val() == "? number:1 ?") { $(".d_qty").val("1"); check_int = parseFloat($(".d_qty").val()); } else { check_int = parseFloat($(".d_qty").val()); $(".d_qty").val(check_int); } return check_int; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems option_id:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems dataVariantsPick:", $scope.dataVariantsPick); if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); console.log("dataVariants :", dataVariants); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; if (dataVariants[i].sku != "") { $scope.product_sku = dataVariants[i].sku; } else { $scope.product_sku = $scope._dataArray.product_sku; } if (dataVariants[i].sku != "") { $scope.product_code = dataVariants[i].barcode; } else { $scope.product_code = $scope._dataArray.product_code; } $scope.product_price = $scope.calculate(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); break; } else { $scope.qty_current_size_state = false; $scope.buy_state = false; $scope.product_price = $scope._dataArray.product_price; $scope.product_compare_price = $scope._dataArray.product_compare_price; $scope.product_sku = $scope._dataArray.product_sku; $scope.product_code = $scope._dataArray.product_code; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope.viewInfo = 1; $scope.view = function(input) { $scope.viewInfo = input; } $scope._getDataArray($scope._getIdUrl()); // setTimeout(function() { // alert($('input[name=radiogroup]:checked').val()); // }, 700); $scope.clickckvalue = function() { var result = 0; $scope.promotion_list = $('input[name=radiogroup]:checked').val(); console.log("promotion_list : ", $scope.promotion_list); if ($('input[name=radiogroup]:checked').val() != "" && $('input[name=radiogroup]:checked').val() != undefined) { result = $('input[name=radiogroup]:checked').val(); } else { result = 0; } return result; } $scope.checkPrice = function(price) { var check_price = 0; var _price = (price != undefined && price != "" && price != null) ? price.toString() : "0"; if (_price.includes(".")) { check_price = 2; } return check_price; }; $scope._isLogin = function() { return UiCustomerBox.delegate.get.isLogin(); }; }; return promise; });_ui_share_app.directive('productDetailPageEd', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageEd'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataTag = false; $scope._dataArray = []; $scope.product_id = ""; $scope.product_sku = ""; $scope.product_code = ""; $scope.product_price = 0; $scope.product_compare_price = 0; $scope.promotion_list = 0; $scope._dataArrayState = { load: true, done: false }; console.log("promotion_list : ", $scope.promotion_list); $scope.dataShopCurrent = []; $scope.dataShopPointConfig = []; $scope.getShopCurrent = function() { var dataSend = {}; GAEAPI.get('shop/current', dataSend).then(function(output) { console.log("getShopCurrent : output : ", output); if (output.ok == 1) { $scope.dataShopCurrent = output.data; console.log("getShopCurrent : dataShopCurrent : ", $scope.dataShopCurrent); $scope.dataShopPointConfig = output.data.shop_point_config; console.log("getShopCurrent : dataShopPointConfig : ", $scope.dataShopPointConfig); } }); }; $scope.getShopCurrent(); $scope.getShopPointConfigRewardState = function(product_price, quantity) { var state = 'RewardShop'; var sup_price = product_price * quantity; if ($scope.dataShopPointConfig.length != 0) { if (parseInt($scope.dataShopPointConfig.er_rate) != 0 && parseInt($scope.dataShopPointConfig.er_earn) != 0) { if (parseInt($scope.dataShopPointConfig.er_rate) <= sup_price) { state = 'RewardShop'; return state; } else { state = 'High'; return state; } } else { return 'RewardProduct'; return state; } } else { return 'RewardProduct'; } }; $scope.getShopPointConfigReward = function(product_price, quantity) { var sup_price = 0; var er_rate = 0; var er_earn = 0; var mathFloor = 0; var point = 0; // console.log("getShopPointConfigReward : shop_point_config.er_rate : ",$scope.dataShopPointConfig.er_rate); if ($scope.dataShopPointConfig.length != 0) { sup_price = product_price * quantity; er_rate = parseInt($scope.dataShopPointConfig.er_rate); er_earn = parseInt($scope.dataShopPointConfig.er_earn); mathFloor = Math.floor(sup_price / er_rate); point = mathFloor * er_earn; return point; } else { return point; } } $scope._getReward = function(datain, product_price, qty) { if (datain.length == 0) { return 'Data Reward Error'; } console.log("_getReward : product_price : ", product_price, " qty : ", qty); var reward = "NULL"; if (datain.reward_type_id == "101") {} else if (datain.reward_type_id == "102") {} else if (datain.reward_type_id == "103") { var reward_every_price = parseInt(datain.reward_every_price); var sum_product_price = Math.round(product_price) * qty; var reward_amount = parseInt(datain.reward_amount); console.log("_getReward : reward_every_price : ", reward_every_price, " sum_product_price : ", sum_product_price, " reward_amount : ", reward_amount); if (reward_every_price <= sum_product_price) { var divided = Math.floor(sum_product_price / reward_every_price); var multiplied = divided * reward_amount; console.log("_getReward : divided : ", divided, " multiplied : ", multiplied); reward = multiplied; } else { reward = "ZERO"; } } else { return 'Data Reward Type Id Error'; } return reward; }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'txt_product_id': id, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; // if ($scope._dataArray.product_is_promotion != 0) { // $scope.promotion_list = $scope._dataArray.product_promotion[0].promotion_id; // } console.log("promotion_list : ", $scope.promotion_list); console.log("_getDataArray _dataArray : ", $scope._dataArray); $scope.product_id = $scope._dataArray.product_id; $scope.dataPreserve = res.data; if (res.data.product_sku != undefined) { $scope.product_sku = res.data.product_sku; } if (res.data.product_code != undefined) { $scope.product_code = res.data.product_code; } $scope.product_price = $scope.calculate(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); if ($scope._dataArray.product_referral_display.category != 'undefined' && $scope._dataArray.product_referral_display.category != null) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.dataTag = res.data.product_tags.split(","); $scope.qtyCurrentSize(res.data.product_total_variant, res.data.product_total_stock); $scope.buildVariantOption(res.data); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.mkCarousel = function(elem) { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { slidesToShow: 1, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var dataSend = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.dataRelation = res.data; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getIdUrl = function() { var getData = []; var returnData = ''; if (typeof $routeParams.product_id !== 'undefined') { getData = $routeParams.product_id; returnData = getData.split("-"); return returnData[0]; } }; $scope._stateReward = function(datain) { var state = false; /* console.log("_stateReward : reward_lifetime : ", datain.reward_lifetime); */ if (datain.length != 0) { state = true; } return state; }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleStatres.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleStatres.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.qtyCurrentSize = function(product_total_variant, product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : product_total_variant : ", product_total_variant, "product_total_stock : ", product_total_stock); if (product_total_variant == 0) { if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; if (product_total_stock >= 20) { for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else { for (var i = 0; i < parseInt(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_stock < 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock == 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else { $scope.qty_current_size_state = false; $scope.buy_state = false; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_variant > 0) { if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < product_total_stock; i++) { $scope.qty_current_size.push(i + 1); } } } $scope.qtyShow($scope.qty_current_size); }; $scope.htmlSelectTime = 0; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } } $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").val() == undefined) { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); check_int = 1; } else if ($(".d_qty").val() == "? number:1 ?") { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); } else { check_int = parseInt($(".d_qty").val()); $(".d_qty").val(check_int); } return check_int; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems option_id:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems dataVariantsPick:", $scope.dataVariantsPick); if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); console.log("dataVariants :", dataVariants); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; if (dataVariants[i].sku != "") { $scope.product_sku = dataVariants[i].sku; } else { $scope.product_sku = $scope._dataArray.product_sku; } if (dataVariants[i].sku != "") { $scope.product_code = dataVariants[i].barcode; } else { $scope.product_code = $scope._dataArray.product_code; } $scope.product_price = $scope.calculate(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); break; } else { $scope.qty_current_size_state = false; $scope.buy_state = false; $scope.product_price = $scope._dataArray.product_price; $scope.product_compare_price = $scope._dataArray.product_compare_price; $scope.product_sku = $scope._dataArray.product_sku; $scope.product_code = $scope._dataArray.product_code; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope.viewInfo = 1; $scope.view = function(input) { $scope.viewInfo = input; } $scope._getDataArray($scope._getIdUrl()); // setTimeout(function() { // alert($('input[name=radiogroup]:checked').val()); // }, 700); $scope.clickckvalue = function() { var result = 0; $scope.promotion_list = $('input[name=radiogroup]:checked').val(); console.log("promotion_list : ", $scope.promotion_list); if ($('input[name=radiogroup]:checked').val() != "" && $('input[name=radiogroup]:checked').val() != undefined) { result = $('input[name=radiogroup]:checked').val(); } else { result = 0; } return result; } }; return promise; });_ui_share_app.directive('productDetailPageEe', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageEe'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataTag = false; $scope._dataArray = []; $scope.product_id = ""; $scope.product_sku = ""; $scope.product_code = ""; $scope.product_price = 0; $scope.product_compare_price = 0; $scope.promotion_list = 0; $scope._dataArrayState = { load: true, done: false }; console.log("promotion_list : ", $scope.promotion_list); $scope.dataShopCurrent = []; $scope.dataShopPointConfig = []; $scope.getShopCurrent = function() { var dataSend = {}; GAEAPI.get('shop/current', dataSend).then(function(output) { console.log("getShopCurrent : output : ", output); if (output.ok == 1) { $scope.dataShopCurrent = output.data; console.log("getShopCurrent : dataShopCurrent : ", $scope.dataShopCurrent); $scope.dataShopPointConfig = output.data.shop_point_config; console.log("getShopCurrent : dataShopPointConfig : ", $scope.dataShopPointConfig); } }); }; $scope.getShopCurrent(); $scope.getShopPointConfigRewardState = function(product_price, quantity) { var state = 'RewardShop'; var sup_price = product_price * quantity; if ($scope.dataShopPointConfig.length != 0) { if (parseInt($scope.dataShopPointConfig.er_rate) != 0 && parseInt($scope.dataShopPointConfig.er_earn) != 0) { if (parseInt($scope.dataShopPointConfig.er_rate) <= sup_price) { state = 'RewardShop'; return state; } else { state = 'High'; return state; } } else { return 'RewardProduct'; return state; } } else { return 'RewardProduct'; } }; $scope.getShopPointConfigReward = function(product_price, quantity) { var sup_price = 0; var er_rate = 0; var er_earn = 0; var mathFloor = 0; var point = 0; // console.log("getShopPointConfigReward : shop_point_config.er_rate : ",$scope.dataShopPointConfig.er_rate); if ($scope.dataShopPointConfig.length != 0) { sup_price = product_price * quantity; er_rate = parseInt($scope.dataShopPointConfig.er_rate); er_earn = parseInt($scope.dataShopPointConfig.er_earn); mathFloor = Math.floor(sup_price / er_rate); point = mathFloor * er_earn; return point; } else { return point; } } $scope._getReward = function(datain, product_price, qty) { if (datain.length == 0) { return 'Data Reward Error'; } console.log("_getReward : product_price : ", product_price, " qty : ", qty); var reward = "NULL"; if (datain.reward_type_id == "101") {} else if (datain.reward_type_id == "102") {} else if (datain.reward_type_id == "103") { var reward_every_price = parseInt(datain.reward_every_price); var sum_product_price = Math.round(product_price) * qty; var reward_amount = parseInt(datain.reward_amount); console.log("_getReward : reward_every_price : ", reward_every_price, " sum_product_price : ", sum_product_price, " reward_amount : ", reward_amount); if (reward_every_price <= sum_product_price) { var divided = Math.floor(sum_product_price / reward_every_price); var multiplied = divided * reward_amount; console.log("_getReward : divided : ", divided, " multiplied : ", multiplied); reward = multiplied; } else { reward = "ZERO"; } } else { return 'Data Reward Type Id Error'; } return reward; }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'txt_product_id': id, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; // if ($scope._dataArray.product_is_promotion != 0) { // $scope.promotion_list = $scope._dataArray.product_promotion[0].promotion_id; // } console.log("promotion_list : ", $scope.promotion_list); console.log("_getDataArray _dataArray : ", $scope._dataArray); $scope.product_id = $scope._dataArray.product_id; $scope.dataPreserve = res.data; if (res.data.product_sku != undefined) { $scope.product_sku = res.data.product_sku; } if (res.data.product_code != undefined) { $scope.product_code = res.data.product_code; } $scope.product_price = $scope.calculate(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); if ($scope._dataArray.product_referral_display.category != 'undefined' && $scope._dataArray.product_referral_display.category != null) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.dataTag = res.data.product_tags.split(","); $scope.qtyCurrentSize(res.data.product_total_variant, res.data.product_total_stock); $scope.buildVariantOption(res.data); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.mkCarousel = function(elem) { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { slidesToShow: 1, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var dataSend = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.dataRelation = res.data; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getIdUrl = function() { var getData = []; var returnData = ''; if (typeof $routeParams.product_id !== 'undefined') { getData = $routeParams.product_id; returnData = getData.split("-"); return returnData[0]; } }; $scope._stateReward = function(datain) { var state = false; /* console.log("_stateReward : reward_lifetime : ", datain.reward_lifetime); */ if (datain.length != 0) { state = true; } return state; }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleStatres.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleStatres.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.qtyCurrentSize = function(product_total_variant, product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : product_total_variant : ", product_total_variant, "product_total_stock : ", product_total_stock); if (product_total_variant == 0) { if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; if (product_total_stock >= 20) { for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else { for (var i = 0; i < parseInt(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_stock < 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock == 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else { $scope.qty_current_size_state = false; $scope.buy_state = false; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_variant > 0) { if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < product_total_stock; i++) { $scope.qty_current_size.push(i + 1); } } } $scope.qtyShow($scope.qty_current_size); }; $scope.htmlSelectTime = 0; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } } $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").val() == undefined) { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); check_int = 1; } else if ($(".d_qty").val() == "? number:1 ?") { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); } else { check_int = parseInt($(".d_qty").val()); $(".d_qty").val(check_int); } return check_int; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems option_id:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems dataVariantsPick:", $scope.dataVariantsPick); if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); console.log("dataVariants :", dataVariants); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; if (dataVariants[i].sku != "") { $scope.product_sku = dataVariants[i].sku; } else { $scope.product_sku = $scope._dataArray.product_sku; } if (dataVariants[i].sku != "") { $scope.product_code = dataVariants[i].barcode; } else { $scope.product_code = $scope._dataArray.product_code; } $scope.product_price = $scope.calculate(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); break; } else { $scope.qty_current_size_state = false; $scope.buy_state = false; $scope.product_price = $scope._dataArray.product_price; $scope.product_compare_price = $scope._dataArray.product_compare_price; $scope.product_sku = $scope._dataArray.product_sku; $scope.product_code = $scope._dataArray.product_code; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope.viewInfo = 1; $scope.view = function(input) { $scope.viewInfo = input; } $scope._getDataArray($scope._getIdUrl()); // setTimeout(function() { // alert($('input[name=radiogroup]:checked').val()); // }, 700); $scope.clickckvalue = function() { var result = 0; $scope.promotion_list = $('input[name=radiogroup]:checked').val(); console.log("promotion_list : ", $scope.promotion_list); if ($('input[name=radiogroup]:checked').val() != "" && $('input[name=radiogroup]:checked').val() != undefined) { result = $('input[name=radiogroup]:checked').val(); } else { result = 0; } return result; } }; return promise; }); _ui_share_app.directive('productDetailPageF', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageF'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; /* JQ: Scroll event */ angular.element($window).bind('scroll',function(){ if(!$scope.data){ return; } var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos", curPos, properHeight); if(curPos > properHeight){ angular.element('.block-background .bottom-info').addClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Slider Send */ $scope.data = false; $scope.dataPreserve = false; /* Get product id from url or from component */ $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; /* Get data by product id */ GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope._getPostIdFromURL()); } }); $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 6, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function () { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('[data-key="'+$scope._uniqueKey+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original=1; $scope.qty_current=1; /* Click SLick Item */ $scope.slickGoto = function (idx) { setTimeout(function () { $('[data-key="'+$scope._uniqueKey+'"]').slick('slickGoTo', idx); }, 100); }; /* Calcu Nav Arrows */ $scope.maxHeight = 0; $scope.navArrowsCalculate=function(){ var size = ($('img.img_gallery').eq(0).height() / 2); $scope.maxHeight = (size + 18); $('img.img_gallery').each(function() { if ($(this).height() > $scope.maxHeight) { $scope.maxHeight = $(this).height(); } }); return '-' + $scope.maxHeight + 'px'; }; $scope.navArrowWidth = function(){ return $('#gallery_display').width() + 'px'; }; }; return promise; }); _ui_share_app.directive('productDetailPageG', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageG'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', headerheight: '@headerheight', controlbutton : '@controlbutton', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* Get product id from url or from component */ $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; $scope.data = false; $scope.dataPreserve = false; /* Get data by product id */ GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; console.log("testtest",$scope.data); $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); /*$scope.buildDataProductRelate($scope._getPostIdFromURL());*/ } }); $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; /*$scope.makeVariantsClick();*/ $scope.makeVaraintsClick_Normal(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.onClickVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; /* Select FIrst Varaint (SELECT) */ $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; /* Select FIrst Varaint (Normal click) */ $scope.makeVaraintsClick_Normal = function(){ $timeout(function(){ $('div.variantSelector').each(function(idx,obj){ $(this).find('[data-index="'+idx+'"]').eq(0).click(); }); },2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function () { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, adaptiveHeight: true, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('[data-key="'+$scope._uniqueKey+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original=1; $scope.qty_current=1; $scope.getShopName = function(){ return (typeof tttt !== 'undefined') ? tttt.shop_name : ''; }; /* Click SLick Item */ $scope.slickGoto = function (idx) { setTimeout(function () { $('#gallery_slider').slick('slickGoTo', idx); }, 100); }; /* Calcu Nav Arrows */ $scope.navArrowsCalculate=function(){ var size = ($('img.img_gallery').eq(0).height() / 2); var n = (size + 18) + 20; return '-' + n + 'px'; }; $scope.navArrowWidth = function(){ return $('#gallery_slider').width() + 'px'; }; }; return promise; }); _ui_share_app.directive('productDetailPageGrip', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageGrip'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0 }; $scope.login = function() { var login = { showLogin: function() { return UiCustomerBox.delegate.get.isLogin(); }, isLogin: function(callback) { callback(UiCustomerBox.delegate.get.isLogin()); }, totalAmount: function() { return UiCart.delegate.get.totalAmount() || 0; }, pageLogin: function() { var _self = this; _self.isLogin(function(isLogin) { if (!isLogin) { $inloginPopupTypeGrip.open(); } }); } } return login; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); } } } return quantity; }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 1000); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log(name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getDataArrayOk: function(output, callback) { var state = false; if (output.ok == 1) { state = true; callback(output, state); } callback(output, state); }, quantity: function(product_stock_track_type_id, product_total_stock, callback) { var total_stock = 0; /* if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } */ if (product_stock_track_type_id == "0") { total_stock = 20; } else if (product_stock_track_type_id == "1") { if (product_total_stock > 0) { total_stock = product_total_stock; } else { total_stock = 0; } } callback(total_stock); }, main: function() { var _self = this; $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { _self.consoleLog("getDataProductArray : output : ", output.data); _self.getDataArrayOk(output, function(output, state) { if (state) { _self.quantity(output.data.product_stock_track_type_id, output.data.product_total_stock, function(total_stock) { $scope.dataProductBuy.quantity_max = (total_stock >= 5) ? 5 : total_stock; _self.consoleLog("getDataProductArray : output : ", output.data); $scope.dataArray = output.data; $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; $scope.dataArrayState = _self.stateData(false, true); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; }); }); } else { $scope.dataArrayState = _self.stateData(false, true); } }); }); } } return data; }; $scope.getDataArray().main(); }; return promise; }); _ui_share_app.directive('productDetailPageH', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageH'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', headerheight: '@headerheight', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; /*angular.element($window).bind('load',function(){ $('.video_container .video_display').click(); });*/ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; /* JQ: Scroll event */ angular.element($window).bind('scroll',function(){ if(!$scope.data){ return; } var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos", curPos, properHeight); if(curPos > properHeight){ angular.element('.block-background .bottom-info').addClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Slider Send */ $scope.data = false; $scope.dataPreserve = false; /* Get product id from url or from component */ $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; /* Get data by product id */ GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); /*$scope.buildDataProductRelate($scope._getPostIdFromURL());*/ } }); $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; /*$scope.makeVariantsClick();*/ }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function () { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('[data-key="'+$scope._uniqueKey+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original=1; $scope.qty_current=1; $scope.qty_change = function(i){ $scope.qty_current = i; console.log("qty_current", i); }; }; return promise; }); _ui_share_app.directive('productDetailPageHub', function($rootScope, $routeParams, $location, sliderProvider) { var templateName = 'productDetailPageHub'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', icon: '@icon', stylebutton: '@stylebutton' }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayTags = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.showTab = { activeTab: 'description', dataTab: [{ state: true, en: 'description', th: 'รายละเอียดสินค้า', data: '' }, { state: true, en: 'info', th: 'วิธีการชำระเงินและวิธีการจัดส่ง', data: '' }] }; $scope.attribute = { state: false, attributeOption: [], variants: 'description', variantsPick: [], dataVariants: [], variantsTotal: 0 }; $scope.buy = { state: false, attribute: false }; $scope.processBuy = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, onClickFalse: function() { if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } } } return functionIn; }; $scope.attributeOption = function() { var functionIn = { consoleLog: function(name, data) { console.log("productDetailPageHub : ", name, data); }, checkVariantsPick: function(variantsPick) { if (variantsPick.length != 0) { var state = 0; for (var i = 0; i < variantsPick.length; i++) { if (variantsPick[i] == "") { state = state + 1; } } if (state == 0) { return true } else { return false } } else { return false } }, compareArray: function(attributeOption, optionJson) { if (!optionJson) return false; if (attributeOption.length != optionJson.length) return false; for (var i = 0, l = attributeOption.length; i < l; i++) { if (attributeOption[i] instanceof Array && optionJson[i] instanceof Array) { if (!compareArray(attributeOption[i], optionJson[i])) return false; } else if (attributeOption[i] != optionJson[i]) { return false; } } return true; }, checkAttributeOption: function(attributeOption, attributeOptionLength, callback) { var _self = this; var attribute = (attributeOption.length == attributeOptionLength) ? true : false; for (var i = 0; i < attributeOption.length; i++) { _self.consoleLog("checkAttributeOption : attributeOption[i] : ", attributeOption[i]); if (attributeOption[i] == undefined) { attribute = false; } } callback(attribute); }, findVariantsData: function(attributeOption, dataVariants, attributeOptionLength, callback) { var _self = this; _self.consoleLog("findVariantsData : attributeOption : ", attributeOption); _self.consoleLog("findVariantsData : dataVariants : ", dataVariants); _self.consoleLog("findVariantsData : attributeOptionLength : ", attributeOptionLength); _self.checkAttributeOption(attributeOption, attributeOptionLength, function(res_attribute_option) { _self.consoleLog("checkAttributeOption : callback : res_attribute_option ", res_attribute_option); var variantsOut = []; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (_self.compareArray(attributeOption, optionJson)) { _self.consoleLog("findVariantsData : dataVariants[i] : ", dataVariants[i]); variantsOut = dataVariants[i]; break; } } callback(variantsOut, res_attribute_option); }); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var _self = this; var state = true; _self.consoleLog("checkTotalStock : index : ", stateIn); _self.consoleLog("checkTotalStock : quantity_max : ", quantity_max); if (stateIn == false && quantity_max > 0) { state = false; } callback(state); }, onClickOption: function($index, option_id) { var _self = this; _self.consoleLog("onClickOption : index : ", $index); _self.consoleLog("onClickOption : option_id : ", option_id); $scope.attribute.variantsPick[$index] = option_id; _self.consoleLog("onClickOption : $scope.attribute.variantsPick[$index] : ", $scope.attribute.variantsPick[$index]); if ($scope.attribute.attributeOption.length >= $scope.attribute.variantsPick.length) { if (_self.checkVariantsPick($scope.attribute.variantsPick)) { _self.consoleLog("onClickOption : if : $scope.attribute.attributeOption.length : ", $scope.attribute.attributeOption.length); _self.consoleLog("onClickOption : if : $scope.attribute.variantsPick.length : ", $scope.attribute.variantsPick.length); _self.findVariantsData($scope.attribute.variantsPick, $scope.attribute.dataVariants, $scope.attribute.attributeOption.length, function(variantsOut, res_attribute_option) { _self.consoleLog("onClickOption : if : findVariantsData : variantsOut : ", variantsOut); _self.consoleLog("onClickOption : if : findVariantsData : res_attribute_option : ", res_attribute_option); if (variantsOut.length != 0 && res_attribute_option) { $scope.dataArray.product_id = variantsOut.product_id; $scope.dataArray.product_sku = variantsOut.sku; $scope.dataProductBuy.price = variantsOut.price; $scope.dataArray.product_compare_price = variantsOut.compare_price; $scope.dataProductBuy.quantity_max = variantsOut.total_stock; if (variantsOut.variant_image != 0) { if ($scope.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataArray.product_image.length; i++) { $scope.dataArray.product_image[i].image_id if ($scope.dataArray.product_image[i].image_id == variantsOut.variant_image[0].image_id) { $scope.slickImageGoto(i); } } } } _self.checkOption($scope.attribute.variantsTotal, function(state) { _self.checkTotalStock(state, variantsOut.total_stock, function(state) { $scope.buy.state = state; if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } }); }); } else if (variantsOut.length == 0 && res_attribute_option) { $scope.dataArray.product_id = 0; $scope.dataArray.product_sku = ''; $scope.dataProductBuy.price = 0; $scope.dataArray.product_compare_price = 0; $scope.dataProductBuy.quantity_max = 1; $scope.buy.state = true; $scope.buy.attribute = true; } $scope.quantity().input(); }); } } } } return functionIn; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity_max; } _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } } } return quantity; }; $scope.carouselId = ''; $scope.slickCarouselId = function() { if ($scope.carouselId == '') { $scope.carouselId = Math.floor((Math.random() * 9999) + 1000); return $scope.carouselId; } else { return $scope.carouselId; } }; $scope.slickImageGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope.carouselId + '"]').slick('slickGoTo', idx); }, 100); }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 100); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log('productDetailPageHub : ', name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getQuantityBreak: function(api, callback) { var _self = this; _self.getProductId(function(product_id) { var customerId = 0; if (UiCustomerBox.delegate.get.isLogin()) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); } var dataSendQuantityBreak = { 'txt_product_id': product_id, 'txt_customer_id': customerId }; var quantity_break = []; _self.getDataArray(api, dataSendQuantityBreak, function(output) { if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); }); }, quantity: function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.dataArray, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } }, showTab: function(input, callback) { var description = input.product_description; var info = input.product_more_info; var state_info = (input.product_is_more_info == 1) ? true : false; callback(description, info, state_info); }, productTab: function(product_tags, callback) { var _self = this; _self.consoleLog("productTab : product_tags : ", product_tags); var productTab = []; if (product_tags != undefined) { if (product_tags != "") { productTab = product_tags.split(","); callback(productTab); } else { callback(productTab); } } else { callback(productTab); } }, getAttribute: function(input, callback) { var _self = this; var attribute = []; var variants = []; var variants_total = 0; _self.consoleLog("getAttribute : input : ", input); if (input.product_attribute.option_data !== 'undefined' && input.product_total_variant > 0) { _self.consoleLog("getAttribute : input.product_attribute.option_data : ", input.product_attribute.option_data); _self.consoleLog("getAttribute : input.product_total_variant : ", input.product_total_variant); if (input.product_attribute.option_data.pclass_array !== 'undefined' && input.product_attribute.option_data.pclass_array.length) { _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array : ", input.product_attribute.option_data.pclass_array); _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array.length : ", input.product_attribute.option_data.pclass_array.length); attribute = input.product_attribute.option_data.pclass_array; variants = input.product_attribute.option_data.variant_array; variants_total = input.product_total_variant; } } callback(variants_total, attribute, variants); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = true; if (stateIn == true && quantity_max > 0) { state = false; } callback(state); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, main: function() { var _self = this; $scope.slickCarouselId(); $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { if (output.data.length != 0) { _self.consoleLog(" : output : ", output.data); _self.quantity(output.data.product_total_stock, function(total_stock) { _self.consoleLog("quantity : total_stock : ", total_stock); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataArray = output.data; _self.productTab(output.data.product_tags, function(productTab) { $scope.dataArrayTags = productTab; _self.showTab(output.data, function(description, info, state_info) { $scope.showTab.dataTab[0].data = description; $scope.showTab.dataTab[1].data = info; $scope.showTab.dataTab[1].state = state_info; }); _self.getAttribute(output.data, function(variants_total, attribute, variants) { _self.consoleLog("getAttribute : variants_total : ", variants_total); _self.consoleLog("getAttribute : attribute : ", attribute); _self.consoleLog("getAttribute : variants : ", variants); _self.checkOption(variants_total, function(state) { _self.checkTotalStock(state, total_stock, function(state) { $scope.buy.state = state; $scope.attribute.attributeOption = attribute; $scope.attribute.dataVariants = variants; $scope.attribute.variantsTotal = variants_total; if (variants_total > 0) { _self.checkPriceMin(variants, function(res_price, res_compare_price) { $scope.dataProductBuy.price = res_price; $scope.dataProductBuy.sumprice = res_price; $scope.dataArray.product_compare_price = res_compare_price; }); } else { $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; } }); }); }); _self.getQuantityBreak('product/quantity_break', function(quantity_break) { _self.consoleLog("getQuantityBreak : output : ", quantity_break); $scope.dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.dataProductBuy.result_price = quantity_break[0].unit_price; } }); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; $scope.dataArrayState = _self.stateData(false, true); }); }); }); } else { window.history.back(); } }); } } return data; }; $scope.getDataArray().main(); $scope.tab_id = 0; $scope.tabId = function(id) { $scope.tab_id = id; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.categoriesData = $scope.routeParams().referral_id || ''; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.checkPrice = function(price) { var check_price = 0; var _price = (price != undefined && price != "" && price != null) ? price.toString() : "0"; if (_price.includes(".")) { check_price = 2; } return check_price; }; }; return promise; });_ui_share_app.directive('productDetailPageI', function ($rootScope, $routeParams, sliderProvider, $http) { var templateName = 'productDetailPageI'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', background:'@background', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.data = false; $scope.dataPreserve = false; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; if(CUR_THEME.data.shop_id == "395"){ var req = { url:"https://gaedemo101.getappeasy.com/store/api/v1/product/id?txt_product_id="+$scope._getPostIdFromURL(), method: "GET", }; $http(req).then(function(res){ if(res.data.ok == 1){ var e = res.data; $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope.id); } }); } else { GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope._getPostIdFromURL()); } }); } $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 6, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; /*$scope.makeVariantsClick();*/ }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ if($index == 0 && option_id == ''){ return GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } console.log("onSelectVariantItems: Yes", $scope.dataPreserve); }; $rootScope.$on('repeatend',function(){ /* Slider Send */ var optionsParmas = { autoplay:true, slidesToShow:1, slidesToScroll:1, dots:false, arrows:false, infinite:true }; var extraOptions = { animate: false }; $timeout(function(){ sliderProvider("#gallery_slider", optionsParmas, "", "", extraOptions); },500); }); /* Slick Events */ $scope._slickGoLeft = function () { setTimeout(function () { $('#gallery_slider').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { setTimeout(function () { $('#gallery_slider').slick('slickNext'); }, 100); }; /* Click SLick Item */ $scope.slickGoto = function (idx) { setTimeout(function () { $('#gallery_slider').slick('slickGoTo', idx); }, 100); }; /* Calcu Nav Arrows */ $scope.navArrowsCalculate=function(){ var size = (500 / 2); var n = (size + 18) + 20; return '-' + n + 'px'; }; $scope.navArrowWidth = function(){ return $('#gallery_slider').width() + 'px'; }; }; return promise; }); _ui_share_app.directive('productDetailPageInfo', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageInfo'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', icon: '@icon', stylebutton: '@stylebutton' }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayTags = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.showTab = { activeTab: 'description', dataTab: [{ en: 'description', th: 'รายละเอียดสินค้า', data: '' }, { en: 'info', th: 'วิธีการชำระเงินและวิธีการจัดส่ง', data: '' }] }; $scope.attribute = { state: false, attributeOption: [], variants: 'description', variantsPick: [], dataVariants: [], variantsTotal: 0 }; $scope.buy = { state: false, attribute: false }; $scope.processBuy = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, onClickFalse: function() { if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } } } return functionIn; }; $scope.attributeOption = function() { var functionIn = { consoleLog: function(name, data) { console.log("productDetailPageMaeju : ", name, data); }, checkVariantsPick: function(variantsPick) { if (variantsPick.length != 0) { var state = 0; for (var i = 0; i < variantsPick.length; i++) { if (variantsPick[i] == "") { state = state + 1; } } if (state == 0) { return true } else { return false } } else { return false } }, compareArray: function(attributeOption, optionJson) { if (!optionJson) return false; if (attributeOption.length != optionJson.length) return false; for (var i = 0, l = attributeOption.length; i < l; i++) { if (attributeOption[i] instanceof Array && optionJson[i] instanceof Array) { if (!compareArray(attributeOption[i], optionJson[i])) return false; } else if (attributeOption[i] != optionJson[i]) { return false; } } return true; }, checkAttributeOption: function(attributeOption, attributeOptionLength, callback) { var _self = this; var attribute = (attributeOption.length == attributeOptionLength) ? true : false; for (var i = 0; i < attributeOption.length; i++) { _self.consoleLog("checkAttributeOption : attributeOption[i] : ", attributeOption[i]); if (attributeOption[i] == undefined) { attribute = false; } } callback(attribute); }, findVariantsData: function(attributeOption, dataVariants, attributeOptionLength, callback) { var _self = this; _self.consoleLog("findVariantsData : attributeOption : ", attributeOption); _self.consoleLog("findVariantsData : dataVariants : ", dataVariants); _self.consoleLog("findVariantsData : attributeOptionLength : ", attributeOptionLength); _self.checkAttributeOption(attributeOption, attributeOptionLength, function(res_attribute_option) { _self.consoleLog("checkAttributeOption : callback : res_attribute_option ", res_attribute_option); var variantsOut = []; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (_self.compareArray(attributeOption, optionJson)) { _self.consoleLog("findVariantsData : dataVariants[i] : ", dataVariants[i]); variantsOut = dataVariants[i]; break; } } callback(variantsOut, res_attribute_option); }); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var _self = this; var state = true; _self.consoleLog("checkTotalStock : index : ", stateIn); _self.consoleLog("checkTotalStock : quantity_max : ", quantity_max); if (stateIn == false && quantity_max > 0) { state = false; } callback(state); }, onClickOption: function($index, option_id) { var _self = this; _self.consoleLog("onClickOption : index : ", $index); _self.consoleLog("onClickOption : option_id : ", option_id); $scope.attribute.variantsPick[$index] = option_id; _self.consoleLog("onClickOption : $scope.attribute.variantsPick[$index] : ", $scope.attribute.variantsPick[$index]); if ($scope.attribute.attributeOption.length >= $scope.attribute.variantsPick.length) { if (_self.checkVariantsPick($scope.attribute.variantsPick)) { _self.consoleLog("onClickOption : if : $scope.attribute.attributeOption.length : ", $scope.attribute.attributeOption.length); _self.consoleLog("onClickOption : if : $scope.attribute.variantsPick.length : ", $scope.attribute.variantsPick.length); _self.findVariantsData($scope.attribute.variantsPick, $scope.attribute.dataVariants, $scope.attribute.attributeOption.length, function(variantsOut, res_attribute_option) { _self.consoleLog("onClickOption : if : findVariantsData : variantsOut : ", variantsOut); _self.consoleLog("onClickOption : if : findVariantsData : res_attribute_option : ", res_attribute_option); if (variantsOut.length != 0 && res_attribute_option) { $scope.dataArray.product_id = variantsOut.product_id; $scope.dataArray.product_sku = variantsOut.sku; $scope.dataProductBuy.price = variantsOut.price; $scope.dataArray.product_compare_price = variantsOut.compare_price; $scope.dataProductBuy.quantity_max = variantsOut.total_stock; if (variantsOut.variant_image != 0) { if ($scope.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataArray.product_image.length; i++) { $scope.dataArray.product_image[i].image_id if ($scope.dataArray.product_image[i].image_id == variantsOut.variant_image[0].image_id) { $scope.slickImageGoto(i); } } } } _self.checkOption($scope.attribute.variantsTotal, function(state) { _self.checkTotalStock(state, variantsOut.total_stock, function(state) { $scope.buy.state = state; if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } }); }); } else if (variantsOut.length == 0 && res_attribute_option) { $scope.dataArray.product_id = 0; $scope.dataArray.product_sku = ''; $scope.dataProductBuy.price = 0; $scope.dataArray.product_compare_price = 0; $scope.dataProductBuy.quantity_max = 1; $scope.buy.state = true; $scope.buy.attribute = true; } $scope.quantity().input(); }); } } } } return functionIn; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity_max; } _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } } } return quantity; }; $scope.carouselId = ''; $scope.slickCarouselId = function() { if ($scope.carouselId == '') { $scope.carouselId = Math.floor((Math.random() * 9999) + 1000); return $scope.carouselId; } else { return $scope.carouselId; } }; $scope.slickImageGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope.carouselId + '"]').slick('slickGoTo', idx); }, 100); }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 100); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log('productDetailPageMaeju : ', name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getQuantityBreak: function(api, callback) { var _self = this; _self.getProductId(function(product_id) { var customerId = 0; if (UiCustomerBox.delegate.get.isLogin()) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); } var dataSendQuantityBreak = { 'txt_product_id': product_id, 'txt_customer_id': customerId }; var quantity_break = []; _self.getDataArray(api, dataSendQuantityBreak, function(output) { if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); }); }, quantity: function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.dataArray, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } }, showTab: function(input, callback) { var description = input.product_description; var info = input.product_more_info; callback(description, info); }, productTab: function(product_tags, callback) { var _self = this; _self.consoleLog("productTab : product_tags : ", product_tags); var productTab = []; if (product_tags != undefined) { if (product_tags != "") { productTab = product_tags.split(","); callback(productTab); } else { callback(productTab); } } else { callback(productTab); } }, getAttribute: function(input, callback) { var _self = this; var attribute = []; var variants = []; var variants_total = 0; _self.consoleLog("getAttribute : input : ", input); if (input.product_attribute.option_data !== 'undefined' && input.product_total_variant > 0) { _self.consoleLog("getAttribute : input.product_attribute.option_data : ", input.product_attribute.option_data); _self.consoleLog("getAttribute : input.product_total_variant : ", input.product_total_variant); if (input.product_attribute.option_data.pclass_array !== 'undefined' && input.product_attribute.option_data.pclass_array.length) { _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array : ", input.product_attribute.option_data.pclass_array); _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array.length : ", input.product_attribute.option_data.pclass_array.length); attribute = input.product_attribute.option_data.pclass_array; variants = input.product_attribute.option_data.variant_array; variants_total = input.product_total_variant; } } callback(variants_total, attribute, variants); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = true; if (stateIn == true && quantity_max > 0) { state = false; } callback(state); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, main: function() { var _self = this; $scope.slickCarouselId(); $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { if (output.data.length != 0) { _self.consoleLog(" : output : ", output.data); _self.quantity(output.data.product_total_stock, function(total_stock) { _self.consoleLog("quantity : total_stock : ", total_stock); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataArray = output.data; _self.productTab(output.data.product_tags, function(productTab) { $scope.dataArrayTags = productTab; _self.showTab(output.data, function(description, info) { $scope.showTab.dataTab[0].data = description; $scope.showTab.dataTab[1].data = info; }); _self.getAttribute(output.data, function(variants_total, attribute, variants) { _self.consoleLog("getAttribute : variants_total : ", variants_total); _self.consoleLog("getAttribute : attribute : ", attribute); _self.consoleLog("getAttribute : variants : ", variants); _self.checkOption(variants_total, function(state) { _self.checkTotalStock(state, total_stock, function(state) { $scope.buy.state = state; $scope.attribute.attributeOption = attribute; $scope.attribute.dataVariants = variants; $scope.attribute.variantsTotal = variants_total; if (variants_total > 0) { _self.checkPriceMin(variants, function(res_price, res_compare_price) { $scope.dataProductBuy.price = res_price; $scope.dataProductBuy.sumprice = res_price; $scope.dataArray.product_compare_price = res_compare_price; }); } else { $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; } }); }); }); _self.getQuantityBreak('product/quantity_break', function(quantity_break) { _self.consoleLog("getQuantityBreak : output : ", quantity_break); $scope.dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.dataProductBuy.result_price = quantity_break[0].unit_price; } }); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; $scope.dataArrayState = _self.stateData(false, true); }); }); }); } else { window.history.back(); } }); } } return data; }; $scope.getDataArray().main(); $scope.tab_id = 0; $scope.tabId = function(id) { $scope.tab_id = id; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.categoriesData = $scope.routeParams().referral_id || ''; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.checkPrice = function(price) { var check_price = 0; var _price = (price != undefined && price != "" && price != null) ? price.toString() : "0"; if (_price.includes(".")) { check_price = 2; } return check_price; }; }; return promise; }); _ui_share_app.directive('productDetailPageK', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageK'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name:'@name', imgpath: '@imgpath', id:'@id', headerheight:'@headerheight', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.getWindowsFit = function(){ var h = (typeof $scope.headerheight !== 'udnefined' && $scope.headerheight != '') ? $scope.headerheight : 80; var a = $(window).height() - 80; return a; }; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; angular.element($window).bind('scroll',function(){ var curPos = ($(document).scrollTop()); /*var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1));*/ var properHeight = $scope.getWindowsFit() * Math.abs(($('div.img_cover').length - 1)); console.log("Cur pos",curPos, properHeight); if(curPos > properHeight){ angular.element('.block-background .bottom-info').addClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Slider Send */ var optionsParmas = { autoplay:true, slidesToShow:1, slidesToScroll:1, dots:true, arrows:false, infinite:true }; var extraOptions = { animate: false }; $timeout(function(){ sliderProvider("#gallery-slider-1", optionsParmas, "", $scope._uniqueKey, extraOptions); },1000); $scope.status_done = true; if(CUR_THEME.data.shop_id == "395"){ var req = { url:"https://gaedemo101.getappeasy.com/store/api/v1/product/id?txt_product_id="+$scope._getPostIdFromURL(), method: "GET", }; $http(req).then(function(res){ if(res.data.ok == 1){ var e = res.data; $scope._data_product_id = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope.id); } }); } else { $('.load-effect').addClass('is-active'); $scope.status_done = true; GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ setTimeout(function () { $scope.status_done = false; }, 300); $scope._data_product_id = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope._getPostIdFromURL()); setTimeout(function () { $('.load-effect').addClass('de-active'); }, 300); setTimeout(function () { $('.load-effect').addClass('loaded'); $('.load-effect').removeClass('is-active de-active'); $('.load-effect').removeClass('loaded'); $('html').removeClass('noscroll noscroll-long'); }, 1300); } }); } $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 6, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; /*$scope.makeVariantsClick();*/ }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ if($index == 0 && option_id == ''){ return GAEAPI.get('product/id',{'txt_product_id':$scope.id}).then(function(e){ if(e.ok == 1){ $scope._data_product_id = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope._data_product_id.product_sku = dataVariants[i].sku; $scope._data_product_id.product_price = dataVariants[i].price; $scope._data_product_id.product_id = dataVariants[i].product_id; $scope._data_product_id.product_compare_price = dataVariants[i].compare_price; break; } } console.log("onSelectVariantItems: Yes", $scope.dataPreserve); }; }; return promise; }); _ui_share_app.directive('productDetailPageKrthai', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageKrthai'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', buyicon: '@buyicon', buytext: '@buytext', viewcarttext: '@viewcarttext', buylogin: '@buylogin', currency: '@currency', checkstaff: '@checkstaff', language: '@language', btnstyle: '@btnstyle', maxstock: '@maxstock', videotext: '@videotext', description: '@description', info: '@info', specification: '@specification', textbrand:'@textbrand', navigationhover: '@navigationhover', imageappcoverchecked: '@imageappcoverchecked', categorylists:'@categorylists', categorylistsurl: '@categorylistsurl', backpage: '@backpage', backpageurl: '@backpageurl', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $location) { $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._component = "productDetailPageKrthai"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._buycol = ($scope.buycol != undefined && $scope.buycol != "") ? parseInt($scope.buycol) : 15; $scope._maxstock = ($scope.maxstock != undefined && $scope.maxstock != "") ? parseInt($scope.maxstock) : 20; $scope._categorylistsurl = ($scope.categorylistsurl != undefined && $scope.categorylistsurl != "") ? $scope.categorylistsurl : "category-lists"; $scope._btnstyle = ($scope.btnstyle != undefined && $scope.btnstyle != "") ? $scope.btnstyle : "filled_button_large"; $scope._buylogin = ($scope.buylogin == "true" || $scope.buylogin == "t") ? true : false; $scope._checkstaff = ($scope.checkstaff == "true" || $scope.checkstaff == "t") ? true : false; $scope._categorylists = ($scope.categorylists != undefined && $scope.categorylists != "") ? $scope.categorylists : "สินค้า"; $scope._currency = ($scope.currency != undefined && $scope.currency != "") ? $scope.currency : "THB"; $scope._buyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope.buyicon : "icnt_outline_cart01_dark.png"; $scope._buytext = ($scope.buytext != undefined && $scope.buytext != "") ? $scope.buytext : "เพิ่มในรถเข็น"; $scope._viewcarttext = ($scope.viewcarttext != undefined && $scope.viewcarttext != "") ? $scope.viewcarttext : "ดูรถเข็น"; $scope._videotext = ($scope.videotext != undefined && $scope.videotext != "") ? $scope.videotext : "Video"; $scope._icebuyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope._icnPath + $scope.buyicon : $scope._icnPath + "icnt_outline_cart01_dark.png"; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; $scope._textbrand = ($scope.textbrand != undefined && $scope.textbrand != "") ? $scope.textbrand : "Brand"; $scope._navigationhover = ($scope.navigationhover != undefined && $scope.navigationhover != "") ? $scope.navigationhover : "primary"; $scope._imageappcoverchecked = ($scope.imageappcoverchecked == "true" || $scope.imageappcoverchecked == "t") ? true : false; $scope._backpage = ($scope.backpage != undefined && $scope.backpage != "") ? $scope.backpage : ""; $scope._backpageurl = ($scope.backpageurl != undefined && $scope.backpageurl != "") ? $scope.backpageurl : ""; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getNamePage: function(arr) { var str = []; for (var i = 0; i < arr.length; i++) { if (i != 0) { str.push(arr[i]); } } return str.join(" "); }, getProductId: function(params, callback) { var _self = this; var product_id = (params.product_id != undefined) ? params.product_id.split("-", 1).join("") : false; _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getReferralId: function(productReferralDisplay, callback) { var _self = this; var referral_id = 0; if (productReferralDisplay.length != 0) { if (productReferralDisplay.category != undefined) { if (productReferralDisplay.category.length != 0) { referral_id = productReferralDisplay.category[0].referral_id } } } callback(referral_id); }, getStaffId: function(staffId, callback) { var _self = this; var res_staff = { staff_id: (staffId != 0 && staffId != '' && staffId != undefined) ? staffId : '0', status: (staffId != 0 && staffId != '' && staffId != undefined) ? true : false } callback(res_staff); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carouselA: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ fade: true, dots: false, arrows: false, infinite: true, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselB: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: true, arrows: true, infinite: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselD: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: false, arrows: true, infinite: true, autoplay: true, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselBar: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: false, arrows: false, infinite: false, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 6, slidesToScroll: 6, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 5, slidesToScroll: 5, } }, { breakpoint: 991, settings: { slidesToShow: 4, slidesToScroll: 4, } }, { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 3, } }] }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, slickCarousel: function(carousel, index) { var _self = this; $scope.setCarousel.index = index; setTimeout(function() { $('[data-key="' + carousel + '"]').slick('slickGoTo', index); }, 100); }, prevIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != 0) ? image_index - 1 : image - 1; _self.consoleLog("prevIndex index", $scope.setCarousel.index); }, nextIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != (image - 1)) ? image_index + 1 : 0; _self.consoleLog("nextIndex index", $scope.setCarousel.index); } } return getFunction; }; $scope.getAttribute = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, productAttribute: function(productAttribute, callback) { var _self = this; var attribute = { option_name: "", option_attribute: [] }; if (productAttribute.option_data != undefined) { if (productAttribute.option_data.variant_array != undefined && productAttribute.option_data.variant_array.length != 0) { for (var a = 0; a < productAttribute.option_data.pclass_array.length; a++) { attribute.option_name = attribute.option_name.concat(productAttribute.option_data.pclass_array[a].pclass_name, " "); } for (var b = 0; b < productAttribute.option_data.variant_array.length; b++) { var product_attribute = { product_id: productAttribute.option_data.variant_array[b].product_id, product_sku: productAttribute.option_data.variant_array[b].sku, product_title: "", product_price: parseFloat(productAttribute.option_data.variant_array[b].price), product_compare_price: parseFloat(productAttribute.option_data.variant_array[b].compare_price), product_total_stock: parseFloat(productAttribute.option_data.variant_array[b].total_stock), product_image: productAttribute.option_data.variant_array[b].variant_image } for (var c = 0; c < productAttribute.option_data.variant_array[b].option_name_array.length; c++) { product_attribute.product_title = product_attribute.product_title.concat(productAttribute.option_data.variant_array[b].option_name_array[c], " "); } attribute.option_attribute.push(product_attribute); } } } _self.consoleLog("productAttribute attribute ", attribute); callback(attribute); }, checkDiscountPrice: function(productDiscount, resPrice, resComparePrice, callback) { var _self = this; var price = 0; var compare_price = 0; if (productDiscount.length == 0) { price = parseFloat(resPrice); compare_price = parseFloat(resComparePrice); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(resPrice) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(resPrice); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(resPrice) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(resPrice); } } callback(price, compare_price); }, checkMinPrice: function(option, callback) { var _self = this; var price_min = parseFloat(option.option_attribute[0].product_price); var compare_price_min = parseFloat(option.option_attribute[0].product_compare_price); var total_stock = parseFloat(option.option_attribute[0].product_total_stock); for (var a = 0; a < option.option_attribute.length; a++) { if (price_min >= parseFloat(option.option_attribute[a].product_price)) { price_min = parseFloat(option.option_attribute[a].product_price); compare_price_min = parseFloat(option.option_attribute[a].product_compare_price); total_stock = parseFloat(option.option_attribute[a].product_total_stock); } } _self.consoleLog("checkPriceMin price_min ", price_min); _self.consoleLog("checkPriceMin compare_price_min ", compare_price_min); _self.consoleLog("checkPriceMin total_stock ", total_stock); callback(price_min, compare_price_min, total_stock); }, getTotalStock: function(totalStock, mixStock, callback) { var _self = this; var total_stock = (totalStock > 0) ? ((totalStock <= mixStock) ? totalStock : mixStock) : ((totalStock == -1) ? mixStock : totalStock); callback(total_stock); }, checkMinPrices: function(api, attribute, callback) { var _self = this; var dataPrice = { product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 } } if (attribute.option_attribute.length == 0) { _self.checkDiscountPrice(api.data.product_discount, api.data.product_price, api.data.product_compare_price, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(api.data.product_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, false); }); }); }); }); }); } else { _self.checkMinPrice(attribute, function(res_price_min, res_compare_price_min, res_total_stock) { _self.checkDiscountPrice(api.data.product_discount, res_price_min, res_compare_price_min, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(res_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, true); }); }); }); }); }); }); } }, priceIncludes: function(price, includes, callback) { var _self = this; var priceToString = (price == null) ? 0 : price; _self.consoleLog('priceIncludes priceToString : ', priceToString); callback(priceToString.toString().includes(includes)); }, checkPrice: function(price, callback) { var _self = this; _self.priceIncludes(price, '.', function(res) { _self.consoleLog("checkPrice res ", res); callback((!res) ? 0 : 2); }); }, onSelectOption: function(productId) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = productId; _self.consoleLog("onSelectOption productId ", productId); $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); for (var a = 0; a < $scope.data.attribute.dataArray.option_attribute.length; a++) { _self.consoleLog("onSelectOption option_attribute ", $scope.data.attribute.dataArray.option_attribute[a]); if ($scope.data.attribute.dataArray.option_attribute[a].product_id == productId) { if ($scope.data.attribute.dataArray.option_attribute[a].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var b = 0; b < $scope.dataApi.product.dataArray.product_image.length; b++) { if ($scope.dataApi.product.dataArray.product_image[b].image_id == $scope.data.attribute.dataArray.option_attribute[a].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, b); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[a].product_price, $scope.data.attribute.dataArray.option_attribute[a].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[a].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); break; } } }, onClickOption: function(index) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.data.attribute.productId = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); if ($scope.data.attribute.dataArray.option_attribute[index].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataApi.product.dataArray.product_image.length; i++) { if ($scope.dataApi.product.dataArray.product_image[i].image_id == $scope.data.attribute.dataArray.option_attribute[index].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, i); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[index].product_price, $scope.data.attribute.dataArray.option_attribute[index].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[index].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); } } return getFunction; }; $scope.getAttributeCustom = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, createArray: function(productCustomTemplates, callback) { var _self = this; var custom_attributes = []; if (productCustomTemplates.templates.length != 0) { angular.forEach(productCustomTemplates.templates, function(item, index) { if (item.option_sets.length != 0) { _self.getAttributes(item.option_sets, function(res_attributes) { custom_attributes = custom_attributes.concat(res_attributes); }); } }); /* if (productCustomTemplates.templates[0].option_sets.length != 0) { _self.getAttributes(productCustomTemplates.templates[0].option_sets, function(res_attributes) { custom_attributes = res_attributes; }); } */ } _self.consoleLog("createArray : productCustomTemplates", productCustomTemplates); _self.consoleLog("createArray : custom_attributes", custom_attributes); callback(custom_attributes, true); }, formatAttribute: function(index, optionSubsetIndex, setType, optionSetArray, callback) { var _self = this; var set_id = (setType == 'attribute') ? optionSetArray.set_id : optionSetArray.subset_id; var attribute = { attribute_index: index, attribute_option_subset_index: optionSubsetIndex, active_option_id: (optionSetArray.option_data.select_id != 0) ? optionSetArray.option_data.select_id : "-1", active_option_index: -1, active_option_index_str: "-1", active_textarea: "", active_array: [], set_id: set_id, name: optionSetArray.name, set_type: optionSetArray.ss_type, option: [] } callback(attribute); }, getOption: function(index, optionDataArray, callback) { var _self = this; var options = { index: index, ss_data_id: optionDataArray.ss_data_id, name: optionDataArray.name, image: optionDataArray.image, price: optionDataArray.price, compare_price: 0, total_stock: 0 } callback(options); }, getActive: function(index, activeOptionId, activeOptionIdIn, optionDataArray, callback) { var _self = this; var actives_index = (optionDataArray.ss_data_id == activeOptionId) ? index : activeOptionIdIn; var actives = (optionDataArray.ss_data_id != activeOptionId) ? "0" : "1"; callback(actives_index, actives); }, getAttributes: function(optionSetArray, callback) { var _self = this; var attributes = []; for (var index = 0; index < optionSetArray.length; index++) { _self.formatAttribute(index, 0, 'attribute', optionSetArray[index], function(res_attribute) { if (optionSetArray[index].option_subsets.length != 0) { for (var option_subset_index = 0; option_subset_index < optionSetArray[index].option_subsets.length; option_subset_index++) { _self.formatAttribute(index, option_subset_index, res_attribute.set_type, optionSetArray[index].option_subsets[option_subset_index], function(res_attribute_sub) { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_subsets[option_subset_index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute_sub.active_option_id, active_option_id, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute_sub.option = options; res_attribute_sub.active_option_index = active_option_id; res_attribute_sub.active_option_index_str = String(active_option_id); res_attribute_sub.active_array = active_option_array; attributes.push(res_attribute_sub); }); } } else { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute.active_option_id, active_option_id, optionSetArray[index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute.option = options; res_attribute.active_option_index = active_option_id; res_attribute.active_option_index_str = String(active_option_id); res_attribute.active_array = active_option_array; attributes.push(res_attribute); } }); } callback(attributes) }, getformatQuantity: function(index, attributeCustom, callback) { var _self = this; var quantity = { name: String(index + 1), dataArray: attributeCustom } callback(quantity); }, onClickRadio: function(index, index_option) { var _self = this; _self.consoleLog("onClickRadio : index", index); _self.consoleLog("onClickRadio : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickRadio : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickDropdown: function(index, index_option) { var _self = this; _self.consoleLog("onClickDropdown : index", index); _self.consoleLog("onClickDropdown : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickDropdown : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickCheckbox: function(index, index_option) { var _self = this; _self.consoleLog("onClickCheckbox : index", index); _self.consoleLog("onClickCheckbox : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i == parseInt(index_option)) ? (($scope.data.attribute_custom.dataArray[index].active_array[i] != "0") ? "0" : "1") : $scope.data.attribute_custom.dataArray[index].active_array[i]; } _self.consoleLog("onClickCheckbox : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); } } return getFunction; }; $scope.getReward = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, momentUnix: function(callback) { var _self = this; var now = moment().unix(); callback(now); }, getCalculator: function(sumProductPrice, reward, callback) { var _self = this; _self.consoleLog("getCalculator : sumProductPrice", sumProductPrice); _self.consoleLog("getCalculator : reward", reward); var point_reward = 0; if (reward.type_id == "100") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } else if (reward.type_id == "101") { point_reward = reward.reward_amount; } else if (reward.type_id == "102") { point_reward = (reward.reward_percent * sumProductPrice.price) / 100; } else if (reward.type_id == "103") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } _self.consoleLog("getCalculator : point_reward", point_reward); callback(point_reward); }, getProductReward: function(now, productReward, callback) { var _self = this; var reward = { reward_length: (productReward.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(productReward.reward_lifetime.lifetime_start_time); reward.lifetime_end_time = parseInt(productReward.reward_lifetime.lifetime_end_time); reward.type_id = productReward.reward_type_id; reward.amount = parseInt(productReward.reward_amount); reward.percent = parseInt(productReward.reward_percent); reward.every_price = parseInt(productReward.reward_every_price); } _self.consoleLog("getProductReward : reward", reward); callback(reward); }, getPointConfig: function(now, shopPointConfig, callback) { var _self = this; var reward = { reward_length: (shopPointConfig.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(shopPointConfig.er_from); reward.lifetime_end_time = parseInt(shopPointConfig.er_to); reward.type_id = "100"; reward.amount = parseInt(shopPointConfig.er_earn); reward.every_price = parseInt(shopPointConfig.er_rate); } _self.consoleLog("getPointConfig : reward", reward); callback(reward); }, checkPointReward: function(reward, callback) { var _self = this; var state = false; if (reward.reward_length) { var start = reward.lifetime_start_time < reward.lifetime_time && reward.lifetime_start_time != 0; var end = (reward.lifetime_end_time != -1) ? reward.lifetime_time <= reward.lifetime_end_time && reward.lifetime_end_time != 0 : true; if (start && end) { if (reward.type_id == "100") { var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } else if (reward.type_id == "101") { var amount = reward.amount != 0; if (amount) { state = true; } } else if (reward.type_id == "102") { var percent = reward.percent != 0; if (percent) { state = true; } } else if (reward.type_id == "103") { var percent = reward.percent != 0; var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } } } callback(state); }, checkReward: function(rewardProduct, rewardPointConfig, callback) { var _self = this; _self.consoleLog("checkReward : rewardProduct", rewardProduct); _self.consoleLog("checkReward : rewardPointConfig", rewardPointConfig); var reward = { type_id: "0", amount: 0, percent: 0, every_price: 0 }; _self.checkPointReward(rewardProduct, function(res_state_product) { _self.checkPointReward(rewardPointConfig, function(res_state_point_config) { if (res_state_point_config) { reward.type_id = rewardPointConfig.type_id; reward.type_id = rewardPointConfig.type_id; reward.amount = rewardPointConfig.amount; reward.percent = rewardPointConfig.percent; reward.every_price = rewardPointConfig.every_price; } else if (res_state_product) { reward.type_id = rewardProduct.type_id; reward.amount = rewardProduct.amount; reward.percent = rewardProduct.percent; reward.every_price = rewardProduct.every_price; } _self.consoleLog("checkReward : reward", reward); callback(reward); }); }); }, checkRewardType: function(productReward, shopPointConfig, callback) { var _self = this; _self.momentUnix(function(now) { _self.getProductReward(now, productReward, function(res_reward_product) { _self.getPointConfig(now, shopPointConfig, function(res_reward_point_config) { _self.checkReward(res_reward_product, res_reward_point_config, function(res_reward) { callback(res_reward); }); }); }); }); }, createReward: function(productReward, shopPointConfig, callback) { var _self = this; _self.consoleLog("createReward : productReward", productReward); _self.consoleLog("createReward : shopPointConfig", shopPointConfig); _self.checkRewardType(productReward, shopPointConfig, function(res_reward) { _self.consoleLog("createReward : res_reward", res_reward); callback(res_reward); }); } } return getFunction; }; $scope.getQuantity = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, upDateReward: function() { var _self = this; }, upDateReward: function() { var _self = this; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); }, upDatePrice: function() { var _self = this; var product_price = $scope.data.product_price.price * $scope.data.quantity.quantity_input; var product_compare_price = $scope.data.product_compare_price.price * $scope.data.quantity.quantity_input; $scope.getAttribute().checkPrice(product_price, function(res_price_ecimals) { $scope.data.sum_product_price.price = product_price; $scope.data.sum_product_price.price_ecimals = res_price_ecimals; $scope.getAttribute().checkPrice(product_compare_price, function(res_compare_price_ecimals) { $scope.data.sum_product_compare_price.price = product_compare_price; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((product_compare_price - product_price) > 0) ? product_compare_price - product_price : 0; $scope.getAttribute().checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.upDateReward(); }); }); }); }, input: function(quantityInput) { var _self = this; quantityInput = (quantityInput == null) ? 1 : parseInt(quantityInput); _self.consoleLog("input : quantityInput", quantityInput); if (quantityInput != null) { if (quantityInput >= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_max; } if (quantityInput <= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } } else { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } _self.upDatePrice(); }, minus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input - 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_min", $scope.data.quantity.quantity_min); if (quantity >= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); }, plus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input + 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_max", $scope.data.quantity.quantity_max); if (quantity <= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); } } return getFunction; }; $scope.getBuy = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getProductId: function(params, callback) { var _self = this; var product_id = params.product_id.split("-", 1).join(""); _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, postApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.post(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, UiCartProductAdd: function(productId, quantityInput, promotionId, customOptions, callback) { quantityInput = (quantityInput > $scope.data.quantity.quantity_max) ? $scope.data.quantity.quantity_max : quantityInput; UiCart.delegate.product.add(productId, quantityInput, promotionId, function(res_data) { callback(res_data); }); }, isLogin: function(callback) { var buy_login = $scope._buylogin; var is_login = UiCustomerBox.delegate.get.isLogin(); var is_state = (buy_login) ? (!is_login) ? true : false : false; callback(is_state); }, formLogin: function(is_state, callback) { if (is_state) { $inloginPopup.open(); } callback(is_state); }, getProductStaffId(staff_id_check, callback) { var res_staff_id_check = staff_id_check; var res_staff_id = $scope.dataApi.product.dataArray.product_staff_id; var res_is_state = (res_staff_id != 0 && res_staff_id != '0' && res_staff_id != undefined) ? true : false; callback(res_staff_id_check, res_staff_id, res_is_state); }, isStaffId: function(staff_id_check, callback) { /* todo */ var _self = this; _self.getProductStaffId(staff_id_check, function(res_staff_id_check, res_staff_id, res_is_state) { callback(res_staff_id_check, res_staff_id, res_is_state); }); }, checkCartDuplicateStaff: function(res_staff_id_check, txt_staff_id, res_is_state, callback) { var _self = this var res_is_state = true; if (res_staff_id_check) { var dataSend = { 'txt_staff_id': txt_staff_id, }; _self.dataSend("cart/duplicate_staff", dataSend, function(res_api, res_dataSend) { _self.postApi(res_api, res_dataSend, function(res_ok, res_api, state) { res_is_state = res_api.data.duplicate; callback(res_is_state); }); }); } else { callback(res_is_state); } }, showAlert: function(res_staff_id_check, res_staff_id, res_is_state, res_api, callback) { var res_state = (res_staff_id_check) ? ((res_api) ? ((res_is_state) ? false : true) : true) : false; if (res_state) { if (!res_api) { if (res_staff_id != '0' && res_staff_id != 0) { $scope.controlAlert().alert('002'); } else { $scope.controlAlert().alert('003'); } } else { if (!res_is_state) { $scope.controlAlert().alert('003'); } } } callback(res_state); }, checkStaff: function(callback) { var _self = this var staff_id_check = $scope._checkstaff; var res_check = false; _self.isStaffId(staff_id_check, function(res_staff_id_check, res_staff_id, res_is_state) { _self.checkCartDuplicateStaff(res_staff_id_check, res_staff_id, res_is_state, function(res_api) { _self.showAlert(res_staff_id_check, res_staff_id, res_is_state, res_api, function(res_state) { res_check = res_state; callback(res_check); }); }); }); }, isProgress: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isProgress(productId)) ? true : false; _self.consoleLog("isProgress : productId", productId); _self.consoleLog("isProgress : state", state); callback(state); }, isSelected: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isSelected(productId)) ? true : false; _self.consoleLog("isSelected : productId", productId); _self.consoleLog("isSelected : state", state); callback(state); }, isSelectedReturn: function(productId) { var _self = this; var ui_cart_state = (UiCart.delegate.product.isSelected(productId)) ? true : false; if (!$scope.setBuy.state_active) { $scope.setBuy.state_active = true; var state_process = $scope.setBuy.state_process; var state_step = $scope.setBuy.state_step; if (ui_cart_state && !state_process && state_step != 4) /* cart */ { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else if (!ui_cart_state && !state_process && state_step != 0) /* unset */ { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } else { $scope.setBuy.state_active = false; } } return ui_cart_state; }, updateState: function(productId) { _self = this; _self.isSelected(productId, function(res_state) { if (res_state) { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } return res_state; }); }, uiCart: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; _self.UiCartProductAdd(productId, quantityInput, promotionId, customOptions, function(res_data) { if (res_data) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; if ($scope._cart == "trumpComponentCarts") { _self.trumpComponentCarts(); } }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }, postApiA: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; var custom_options = {}; var dataSend = { 'txt_product_id': productId, 'txt_amount': quantityInput, 'txt_is_clear_cart_before': "0", 'txt_custom_options_json': JSON.stringify(custom_options) }; _self.dataSend("cart/product_add", dataSend, function(res_api, res_dataSend) { _self.postApi(res_api, res_dataSend, function(res_ok, res_api, state) { if (res_ok) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }); }, onProcess: function(data, productId, quantityInput, promotionId, customOptions) { var _self = this; _self.isLogin(function(res_is_login) { _self.formLogin(res_is_login, function(res_form) { _self.checkStaff(function(res_is_state) { if (!$scope.setBuy.state_process && !res_form && !res_is_state) { $scope.setBuy.state_process = true; _self.isSelected(productId, function(res_state) { if (!res_state) { _self.onLoad($scope.setBuy.state_step, function(res_step) { if (data.sum_product_price.price != 0 && data.quantity.quantity_max != 0 && (data.attribute.state == (data.attribute.productId != ''))) { /* UiCart */ _self.uiCart(productId, quantityInput, promotionId, customOptions, res_step); /* api post offline */ /*_self.postApiA(productId, quantityInput, promotionId, customOptions, res_step); */ } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); } else { $scope.setBuy.state_process = false; if ($scope._cart == "trumpComponentCarts") { _self.trumpComponentCarts(); } else if ($scope._cart == "viewcart") { _self.viewCart($scope._cart); } } }); } }); }); }); }, onTimeout: function(time, callback) { var _self = this; var load = $timeout(function() { $timeout.cancel(load); callback(true) }, time); }, onUnset: function(step, callback) { var _self = this; step = (step == 0) ? 0 : 0; $scope.setBuy.state_step = step; callback(step); }, onLoad: function(step, callback) { var _self = this; step = (step == 0 || step == 1) ? 1 : 0; $scope.setBuy.state_step = step; callback(step); }, onPass: function(step, callback) { var _self = this; step = (step == 1 || step == 2) ? 2 : 0; $scope.setBuy.state_step = step; callback(step); }, onError: function(step, callback) { var _self = this; step = (step == 1 || step == 3) ? 3 : 0; $scope.setBuy.state_step = step; callback(step); }, onCart: function(step, callback) { var _self = this; step = (step == 2 || step == 4) ? 4 : 0; $scope.setBuy.state_step = step; callback(step); }, trumpComponentCarts: function() { var controlCart = share.getTrumpComponentCarts(); var component_carts = $('.cover-cards').hasClass('active'); if (!component_carts) { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.cart(); } } else { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.load(); } } }, viewCart: function(viewcart) { var _self = this; _self.pageUrl(viewcart); }, locationUrlReplace: function(page) { $location.url(page).replace(); }, pageUrl: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page); }, main: function(callback) { var _self = this; } } return getFunction; }; $scope.getDetail = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getDetail: function(api, callback) { var _self = this; var description = api.product_description; var info = api.product_more_info; var specificatio = api.product_custom_title;/* [] */ /* if (api.product_attribute.specification_data != undefined) { specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? api.product_attribute.specification_data.pclass_array : []; } */ var state_specificatio = true;/* false */ /* if (api.product_attribute.specification_data != undefined) { state_specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? true : false; }*/ var state_info = true;/* (api.product_is_more_info == 1) ? true : false; */ _self.consoleLog("getDetail : api", api); _self.consoleLog("getDetail : description", description); _self.consoleLog("getDetail : info", info); _self.consoleLog("getDetail : state_info", state_info); _self.consoleLog("getDetail : specificatio", specificatio); _self.consoleLog("getDetail : state_specificatio", state_specificatio); callback(description, info, state_info, specificatio, state_specificatio); }, onClickDetail: function(index) { var _self = this; $scope.data.detail.active = index; _self.consoleLog("onClickDetail : data.detail.active", $scope.data.detail.active); } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageName: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page_name); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.countDown = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getLocation: function(callback) { var _self = this; var res_location = $location; _self.consoleLog("getLocation", "res_location", res_location); callback(res_location); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; _self.consoleLog("getRouteParams", "params", params); callback(params); }, getLocationUrlNameProductDetail: function(callback) { var _self = this; _self.getRouteParams(function(res_params) { _self.getLocation(function(res_location) { var url_page_name = "/product-detail/" + res_params.product_id; var res_url_name_product_detail = (res_location.url() == url_page_name) ? true : false; _self.consoleLog("getLocationUrlNameProductDeal", "res_url_name_product_detail", res_url_name_product_detail); callback(res_url_name_product_detail); }); }); }, getUnix: function(callback) { var _self = this; var now = moment().unix(); _self.consoleLog("getUnix", "now", now); callback(now); }, getCountDown: function(now, product_lifetime, callback) { var _self = this; var countdown_unix = parseInt(product_lifetime.lifetime_end_time) - now; var milliseconds = moment.duration(countdown_unix * 1000, "milliseconds"); var res_countdown = ((milliseconds.days() <= 9) ? '0' + milliseconds.days() : milliseconds.days()); res_countdown = res_countdown + ' : ' + ((milliseconds.hours() <= 9) ? '0' + milliseconds.hours() : milliseconds.hours()); res_countdown = res_countdown + ' : ' + ((milliseconds.minutes() <= 9) ? '0' + milliseconds.minutes() : milliseconds.minutes()); res_countdown = res_countdown + ' : ' + ((milliseconds.seconds() <= 9) ? '0' + milliseconds.seconds() : milliseconds.seconds()); _self.consoleLog("getCountDown", "res_countdown", res_countdown); callback(res_countdown, countdown_unix); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page); }, countDownByProduct: function(now, data_array, callback) { var _self = this; if (data_array.length != 0) { if (data_array.product_lifetime.length != 0) { _self.getCountDown(now, data_array.product_lifetime, function(res_count_down, res_countdown_unix) { data_array.product_lifetime.lifetime_countdown = (res_countdown_unix > 0) ? res_count_down : ""; if (data_array.product_lifetime.lifetime_countdown == "") { _self.getNameUrl(data_array.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", data_array.product_set_array[0].product_id, res_name); }); } }); } } _self.consoleLog("countDownByProduct", "data_array", data_array); callback(data_array); }, loop: function() { var _self = this; var load = $timeout(function() { $timeout.cancel(load); _self.getUnix(function(res_now) { _self.countDownByProduct(res_now, $scope.dataApi.product.dataArray, function(data_array) { $scope.dataApi.product.dataArray = data_array; _self.getLocationUrlNameProductDetail(function(res_url_name_product_detail) { if (res_url_name_product_detail) { _self.loop(); } }); }); }); }, 1000); } } return getFunction; }; $scope.getPromotion = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, setPromotionId: function(promotion_id) { var _self = this; _self.consoleLog("setPromotionId", "promotion_id", promotion_id); $scope.data.promotion.promotion_id = promotion_id; _self.consoleLog("setPromotionId", "data.promotion.promotion_id", $scope.data.promotion.promotion_id); }, } return getFunction; }; $scope.control = function() { var getFunction = { popupVideo: function(state, video_link, video_embed_code) { var _self = this; if (video_embed_code != '') { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } else if (video_link != '') { window.open(video_link, '_blank'); } else { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } }, main: function() { var _self = this; } } return getFunction; }; $scope.data_control = { page_video: { popup: false, shop_video_embed_code: "" } } $scope.control_alert = { alert: { error_id: '', index: null, state: true, error: [{ id: '001', title: 'การสั่งซื้อ', messages: 'สามารถสั่งซื้อได้เพียงทีละออเดอร์เท่านั้น' }, { id: '002', title: 'การเพิ่มสินค้า', messages: 'ไม่สามารถเพิ่มสินค้าของร้านมากกว่า 1 ร้านค้าได้' }, { id: '003', title: 'การสั่งซื้อ', messages: 'ไม่สามารถเพิ่มสินค้า(ไม่มีร้านค้า)' }] } }; $scope.controlAlert = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getErrorMessages: function(error_id, callback) { var _self = this; var messages = { res_error_id: '', res_index: null } angular.forEach($scope.control_alert.alert.error, function(item, index) { if (item.id == error_id) { messages.res_error_id = item.id; messages.res_index = index; } }); callback(messages.res_error_id, messages.res_index); }, alert: function(error_id) { var _self = this; _self.getErrorMessages(error_id, function(res_error_id, res_index) { $scope.control_alert.alert.error_id = res_error_id; $scope.control_alert.alert.index = res_index; $scope.control_alert.alert.state = (!$scope.control.alert && res_error_id != '') ? true : false; }); }, main: function() { var _self = this; } } return getFunction; }; $scope.countDown().loop(); /* set carousel */ $scope.setCarousel = { carousel: 0, index: 0 }; $scope.getCarousel().getCarousel($scope.setCarousel.carousel, function(res_carousel_id) { $scope.setCarousel.carousel = res_carousel_id; }); /* set carousel */ /* get product api */ $scope.dataApi = { reward: { dataSend: {}, api: "shop/current", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, staff: { dataSend: { txt_staff_id: 0 }, api: "staff/id", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, product: { dataSend: { txt_product_id: 0 }, api: "product/id", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, relation: { dataSend: { txt_referral_id: 0 }, api: "referral/relation", ok: false, dataArray: [], dataArrayState: { load: false, done: false } } }; $scope.data = { attribute: { state: false, productId: "", dataArray: [] }, attribute_custom: { state: false, dataArray: [] }, reward: { quantity_name: 'reward', type_id: "0", reward_amount: 0, reward_percent: 0, reward_every_price: 0, point_reward: 0 }, quantity: { quantity_name: 'quantity', quantity_min: 1, quantity_max: 1, quantity_input: 1, quantity_select: [] }, product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, detail: { active: '0', dataArray: [{ index: '0', state: true, en: ($scope.description != undefined && $scope.description != "") ? $scope.description : 'Description', th: '', data: '', dataArray: [] }, { index: '1', state: true, en: ($scope.info != undefined && $scope.info != "") ? $scope.info : 'Info', th: '', data: '', dataArray: [] }, { index: '2', state: true, en: ($scope.specification != undefined && $scope.specification != "") ? $scope.specification : 'Specification', th: '', data: '', dataArray: [] }] }, promotion : { promotion_id : '0' } }; $scope.setBuy = { state_active: false, state_process: false, state_step: 0, state_data_font_color: "", state_data_background_color: "", stepArray: [{ step: 0, name: "unset", icon: $scope._icebuyicon, state: $scope._buytext, data_font_color: "", data_background_color: "" }, { step: 1, name: "load", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 2, name: "pass", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 3, name: "error", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 4, name: "cart", icon: "", state: $scope._viewcarttext, data_font_color: "", data_background_color: "primary_darkest" }] }; /* - get api product/id start - */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.product.dataArrayState = res_state; $scope.getData().getProductId(res_params, function(res_product_id) { $scope.dataApi.product.dataSend.txt_product_id = (res_product_id != false) ? res_product_id : 0; $scope.getData().dataSend($scope.dataApi.product.api, $scope.dataApi.product.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_product, res_state) { $scope.dataApi.product.ok = res_ok; if ($scope._imageappcoverchecked) { var images = []; angular.forEach(get_res_api_product.data.product_image,function(image,index_image){ if (!image.image_app_cover_checked) { images.push(image) } }); get_res_api_product.data.product_image = images; } angular.element('.load-effect').removeClass('is-active'); $scope.dataApi.product.dataArray = get_res_api_product.data; $scope.getData().consoleLog("get_res_api_product", get_res_api_product); $scope.dataApi.product.dataArrayState = res_state; /* -- get api shop/current to reward -- */ if (res_ok) { $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.reward.dataArrayState = res_state; $scope.getData().dataSend($scope.dataApi.reward.api, $scope.dataApi.reward.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_shop, res_state) { $scope.dataApi.reward.ok = res_ok; $scope.dataApi.reward.dataArray = get_res_api_shop.data; $scope.dataApi.reward.dataArrayState = res_state; $scope.getReward().createReward($scope.dataApi.product.dataArray.product_reward, get_res_api_shop.data.shop_point_config, function(res_reward) { $scope.data.reward.type_id = res_reward.type_id; $scope.data.reward.reward_amount = res_reward.amount; $scope.data.reward.reward_percent = res_reward.percent; $scope.data.reward.reward_every_price = res_reward.every_price; /* --- Wait product/id ,shop/current --- */ /* ---- get attribute ---- */ $scope.getAttribute().productAttribute(get_res_api_product.data.product_attribute, function(res_attribute) { $scope.data.attribute.dataArray = res_attribute; $scope.getAttribute().checkMinPrices(get_res_api_product, res_attribute, function(res_data_price, res_state) { $scope.data.attribute.state = res_state; $scope.data.product_price = res_data_price.product_price; $scope.data.product_compare_price = res_data_price.product_compare_price; $scope.data.sum_product_price = res_data_price.sum_product_price; $scope.data.sum_product_compare_price = res_data_price.sum_product_compare_price; $scope.data.sum_product_compare_minus_sum_product_price = res_data_price.sum_product_compare_minus_sum_product_price; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); /* ----- stock ----- */ $scope.data.quantity.quantity_max = res_data_price.product_price.total_stock; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_data_price.product_price.total_stock; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* ----- stock ----- */ }); }); /* ---- get attribute ---- */ /* ---- get attribute custom ---- */ $scope.getAttributeCustom().createArray(get_res_api_product.data.product_custom_templates, function(res_custom_attribute, res_state) { $scope.data.attribute_custom.state = res_state; $scope.data.attribute_custom.dataArray = res_custom_attribute; }); /* ---- get attribute custom ---- */ /* ---- get detail ---- */ $scope.getDetail().getDetail(get_res_api_product.data, function(res_description, res_info, res_state_info, res_specificatio, res_state_specificatio) { $scope.data.detail.dataArray[0].data = res_description; $scope.data.detail.dataArray[1].data = res_info; $scope.data.detail.dataArray[1].state = res_state_info; $scope.data.detail.dataArray[2].data = res_specificatio; $scope.data.detail.dataArray[2].state = res_state_specificatio; }); /* ---- get detail ---- */ /* ---- update state ---- */ $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); /* ---- update state ---- */ /* --- Wait product/id ,shop/current --- */ }); }); }); }); /* -- get api shop/current to reward -- */ /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.relation.dataArrayState = res_state; $scope.getData().getReferralId(get_res_api_product.data.product_referral_display, function(res_referral_id) { $scope.dataApi.relation.dataSend.txt_referral_id = res_referral_id; $scope.getData().dataSend($scope.dataApi.relation.api, $scope.dataApi.relation.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_referral, res_state) { $scope.dataApi.relation.ok = res_ok; $scope.dataApi.relation.dataArray = (res_referral_id != 0) ? get_res_api_referral.data : []; $scope.dataApi.relation.dataArrayState = res_state; }); }); }); }); /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ /* -- product_staff_id from product/id to txt_staff_id get api staff/id -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.getData().getStaffId(get_res_api_product.data.product_staff_id, function(res_staff) { if (res_staff.status) { $scope.dataApi.staff.dataArrayState = res_state; $scope.dataApi.staff.dataSend.txt_staff_id = res_staff.staff_id; $scope.getData().dataSend($scope.dataApi.staff.api, $scope.dataApi.staff.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, res, res_state) { $scope.dataApi.staff.ok = res_ok; $scope.dataApi.staff.dataArray = res.data; $scope.getData().getNameUrl(res.data.staff_first_name, function(res_staff_first_name_url) { $scope.dataApi.staff.dataArray.staff_first_name_url = res_staff_first_name_url; $scope.dataApi.staff.dataArrayState = res_state; }); }); }); } }); }); /* -- product_staff_id from product/id to txt_staff_id get api staff/id -- */ } else { /* ok = false */ if ($scope.dataApi.product.dataArray.length != 0) { /* product deal to product original */ if ($scope.dataApi.product.dataArray.product_set_array.length != 0) { $scope.countDown().getNameUrl($scope.dataApi.product.dataArray.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", $scope.dataApi.product.dataArray.product_set_array[0].product_id, res_name); }); } else { $scope.pages().pageName("home"); } } else { /* product null */ $scope.pages().pageName("home"); } } }); }); }); }); /* - get api product/id end - */ /* get product api */ }; return promise; }); var $xZoomTimer = null; var $xZoomInstance = false; _ui_share_app.directive('productDetailPageL', function ($rootScope, $routeParams, sliderProvider, $http) { var templateName = 'productDetailPageL'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', background:'@background', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.data = false; $scope.dataPreserve = false; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; if(CUR_THEME.data.shop_id == "395"){ var req = { url:"https://gaedemo101.getappeasy.com/store/api/v1/product/id?txt_product_id="+$scope._getPostIdFromURL(), method: "GET", }; $http(req).then(function(res){ if(res.data.ok == 1){ var e = res.data; $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope.id); } }); } else { GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope._getPostIdFromURL()); } }); } $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 6, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; /*$scope.makeVariantsClick();*/ }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ if($index == 0 && option_id == ''){ return GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ console.log("findVariantsData", dataVariants[i]); $scope.data.product_id = dataVariants[i].product_id; /* Warning */ $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } console.log("onSelectVariantItems: Yes", $scope.dataPreserve); }; $rootScope.$on('repeatend',function(){ /* Slider Send */ /*var optionsParmas = { autoplay:true, slidesToShow:1, slidesToScroll:1, dots:false, arrows:false, infinite:true }; var extraOptions = { animate: false }; $timeout(function(){ sliderProvider("#gallery_slider", optionsParmas, "", "", extraOptions); },500); $timeout(function(){ $('.gallery_show_single img').xzoom({ Xoffset: 30, tint: '#b9b5b3', }); },500);*/ }); /* Slick Events */ $scope._slickGoLeft = function () { setTimeout(function () { $('#gallery_slider').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { setTimeout(function () { $('#gallery_slider').slick('slickNext'); }, 100); }; /* Click SLick Item */ $scope.slickGoto = function (idx) { setTimeout(function () { $('#gallery_slider').slick('slickGoTo', idx); }, 100); }; /* Calcu Nav Arrows */ $scope.navArrowsCalculate=function(){ var size = (500 / 2); var n = (size + 18) + 20; return '-' + n + 'px'; }; $scope.navArrowWidth = function(){ return $('#gallery_slider').width() + 'px'; }; /* Optimize image size by device pixel * @params {size} (integer) prefer size * @params {image_url} (string) original image source link * @params {image_width} (string) original image width * @return string */ $scope.viewOptimizeImage = function(size, image_url, image_width){ if(window.devicePixelRatio >= 2 || parseInt(image_width) <= size){ return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't'+size+'_' + b; return a.join("/"); }; $scope.gallerySingleViewIndex = 0; $scope.switchSingleView = function(idx){ console.log("$xZoomInstance",$xZoomInstance); $('.gallery_show_single').css({'transition':'all 0.3s','opacity':'0'}); $timeout(function(){ $scope.gallerySingleViewIndex = idx; $('.gallery_show_single').css({'opacity':'1'}); },300); setTimeout(function(){ if($(window).width() >= 992){ if($("img.zoom").attr('data-api-width') > 400 && $("img.zoom").attr('data-api-height') > 400){ /*$("img.zoom").ezPlus({ 'scrollZoom':true, 'responsive':true, 'zoomWindowWidth':400, 'zoomWindowHeight':400, 'zoomWindowOffetx':30, });*/ $xZoomInstance = $('.zoom').xzoom({ Xoffset: 30, tint: '#b9b5b3', }); } } },300); }; $scope.viewImg = function(i){ window.location.href=i; }; }; return promise; }); _ui_share_app.directive('productDetailPageM', function ($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageM'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window, $http) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.qtyProduct = 1; $scope.data = false; $scope.dataPreserve = false; $scope.data_min = []; $scope.tags_product = []; $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; var dataSend = { 'txt_product_id': $scope._getPostIdFromURL(), }; $scope.data_video_id = false; if(CUR_THEME.shop_id()=="541"){ $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/id", { params: dataSend }).then(function(res){ var e = res.data; if(e.ok == 1){ console.log("product_set_array : data",e.data); $scope.data = e.data; $scope.dataPreserve = e.data; $scope._getSupportDataCategory('category', e.data); $scope.buildDataProductRelate($scope._getPostIdFromURL()); console.log("product_set_array : data",e.data); $scope.data_video_id = $scope.data.product_id; if(e.data.product_tags.length > 0){ $scope.tags_product = e.data.product_tags.split(","); $scope.buildDataProductRelate(e.data.product_tags); } if(e.data.product_attribute.option_data != 0 && e.data.product_total_variant > 0){ if (e.data.product_attribute.option_data.variant_array.length != 0 && e.data.product_total_variant > 0) { var set_varia0 = e.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < e.data.product_attribute.option_data.variant_array.length; i++) { if(parseInt(set_varia0) >= parseInt(e.data.product_attribute.option_data.variant_array[i].price)){ set_varia0 = e.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = e.data.product_attribute.option_data.variant_array[i]; } } if($scope.data_min.length == 0){ $scope.data_min = e.data.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ",$scope.data_min); $scope.buildVariantOption(e.data); $scope.buildMultipleQuantity(e.data); } } if(e.data.product_total_variant == 0 && e.data.product_total_stock > 0){ $scope.names = []; for (var i = 0; i < parseInt(e.data.product_total_stock); i++) { $scope.names.push(i+1); } console.log("nnames stock :",$scope.names); } if(e.data.product_total_variant == 0 && e.data.product_total_stock < 0){ $scope.names = []; for (var i = 0; i < 20; i++) { $scope.names.push(i+1); } console.log("nnames stock :",$scope.names); } if(e.data.product_total_variant > 0){ $scope.names = []; for (var i = 0; i < 20; i++) { $scope.names.push(i+1); } } if (typeof $scope.data.product_attribute.option_data !== 'undefined' && $scope.data.product_total_variant > 0) { if (typeof $scope.data.product_attribute.option_data.pclass_array !== 'undefined' && $scope.data.product_attribute.option_data.pclass_array.length) { // $scope.buildMultipleQuantity(e.data); } } } }); }else{ $componentProductDetail.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()}, function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.data_video_id = $scope.data.product_id; $scope._getSupportDataCategory('category', e.data); // $scope.buildDataProductRelate($scope._getPostIdFromURL()); if(e.data.product_tags.length > 0){ $scope.buildDataProductRelate(e.data.product_tags); } if (typeof $scope.data.product_attribute.option_data !== 'undefined' && $scope.data.product_total_variant > 0) { if (typeof $scope.data.product_attribute.option_data.pclass_array !== 'undefined' && $scope.data.product_attribute.option_data.pclass_array.length) { $scope.buildVariantOption(e.data); } } } }); }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.ifOptionUnSelect = function() { return ($('.d_qty_price.active.inin').length > 0) ? true : false; }; $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {"tags":product_id,'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 8, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d).then(function(e){ if(e.ok == 1){ /*$scope.dataRelate = e.data.dataList;*/ var d = []; angular.forEach(e.data.dataList, function(item){ if(item.product_id !== $scope.data.product_id){ d.push(item); } }); $scope.dataRelate = d; } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.onSelectVariantItems(0, ''); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { $scope.testyuyu = 0; if (option_id == '') { $scope.testyuyu = 0; $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); $('.d_qty').removeClass('active').removeClass('inin'); $('.dsetting').addClass("active"); $('.d_qty_not_result').addClass("active"); $scope.dataVariantsPick[$index] = option_id; console.log("check_vareian 1000:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length); return GAEAPI.get('product/id', { 'txt_product_id': $scope._idUrl($routeParams.product_id) }).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; for (var i = 0; i < $scope.dataVariantsPick.length; i++) { if ($scope.dataVariantsPick[i] != undefined && $scope.dataVariantsPick[i] != "") { $scope.testyuyu++; } } if ($scope.testyuyu >= $scope.dataOption.length) { $scope.testyuyu = 0; $('.d_qty_not_result').removeClass("active"); $('.dsetting').removeClass("active"); $scope.findVariantsData($scope.dataVariantsPick); } else { $scope.testyuyu = 0; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); } console.log("check_vareian 1001:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length, $scope.electric); } }; $scope.findVariantsData = function(variantsPick) { var count = 0; $scope._data_qty_model = 1; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var _self = dataVariants[i]; var _self_option = angular.fromJson(_self.option_id_json); var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope.name_qty = []; $scope.data.product_id = dataVariants[i].product_id; // $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; $scope.data.product_total_stock = dataVariants[i].total_stock; console.log("selectedOptionTextJson: option",$scope.data.product_price); for (var i = 0; i < parseInt($scope.data.product_total_stock); i++) { $scope.name_qty.push(i+1); } console.log("auysuwgdhsdgsh :",$scope.name_qty , $scope._data_qty_model); $scope.switchQuantityByKey('-' + variantsPick.join('-') + '-'); // name_qty console.log("selectedOptionTextJson: option", _self); if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope.data.product_image.length; im++) { if ($scope.data.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } $timeout(function() { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { $scope._slickGoto('gallery_show', rightImagePosition); } else { angular.element('.gallery-thumbnail .thumb-img[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300); } break; } if(!compareArray(variantsPick, optionJson)){ count++; } if(count >= dataVariants.length){ // alert(count); // $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = 0; $scope.data.product_compare_price = 0; } } // alert(count); }; $rootScope.$on('repeatend',function(){ /* Slider Send */ var optionsParmas = { autoplay:true, slidesToShow:1, slidesToScroll:1, dots:false, arrows:false, infinite:true }; var extraOptions = { animate: false }; $timeout(function(){ sliderProvider("#gallery_slider", optionsParmas, "", "", extraOptions); },500); }); /* Slick Events */ $scope._slickGoLeft = function () { $timeout(function () { $('#gallery_slider').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('#gallery_slider').slick('slickNext'); }, 100); }; /* Click SLick Item */ $scope.slickGoto = function (idx) { $timeout(function () { $('#gallery_slider').slick('slickGoTo', idx); }, 100); }; /* Calcu Nav Arrows */ $scope.navArrowsCalculate=function(){ var size = (500 / 2); var n = (size + 18) + 20; return '-' + n + 'px'; }; $scope.navArrowWidth = function(){ return $('#gallery_slider').width() + 'px'; }; /* Build title for Address link*/ $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice){ var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.support_data = { category: [], }; $scope._getSupportDataCategory = function(type,data){ var dataSend = { 'txt_referral_id': data.product_referral_display.category[0].referral_id }; GAEAPI.get('referral/relation',dataSend).then(function(e){ if(e.ok == 1){ $scope.support_data.category = e.data; } }); }; /* Optimize image size by device pixel * @params {size} (integer) prefer size * @params {image_url} (string) original image source link * @params {image_width} (string) original image width * @return string */ $scope.viewOptimizeImage = function(size, image_url, image_width){ if(window.devicePixelRatio >= 2 || parseInt(image_width) <= size){ return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't'+size+'_' + b; return a.join("/"); }; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem){ var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 16: case 72: case 74: case 75: s = true; break; default: s = false; break; } return s; }; $scope.newLoginregister = function(name){ window.location.href=GURL.base_url()+name; }; $scope.invited = []; $scope.insertinvited = function(user) { if(user) { if(user.product_attribute.length != 0){ if($scope.invited[0] == user.product_id){ return; } $scope.invited.push(user.product_id); }else{ alert("item can't compare"); } } else { console.log("test_array :",$scope.invited); } }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem){ var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch(r){ case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; $scope.data_viewTab = 1; $scope._viewTab = function(index){ $scope.data_viewTab = index; }; $scope._data_qty_model = 1; $scope._data_qty_selected = 1; $scope.currentOptionQtyPick = function(variant_key) { var e=1; // var e = angular.element('input[name="detail_qty"]'); // if (typeof variant_key !== 'undefined') { // e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); // } if ($('#detail_qty[variant-key="' + variant_key + '"]').val() != undefined && $('#detail_qty[variant-key="' + variant_key + '"]').val() != '' && isNaN($('#detail_qty[variant-key="' + variant_key + '"]').val())) { e = parseInt($('#detail_qty[variant-key="' + variant_key + '"]').val().substr(7)); console.log("sudyusdysudysyususu :",e); } // if(isNaN(e)){ // e = 1; // } // alert(e); return e; }; $scope.watchQty = function(variant_key) { var e = angular.element('select[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('select[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt($('#detail_qty[variant-key="' + variant_key + '"]').val().substr(7)); console.log("data_set array test : ",i); $scope._data_qty_selected = i; // parseInt(e.val()); // alert(i); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.productQuantityMultiArray = []; $scope.lastCheckedVariantKey = ''; $scope.buildMultipleQuantity = function(productObj) { $scope.productQuantityMultiArray = []; var r = [], p = productObj.product_attribute.option_data.variant_array; for (var i = 0; i < p.length; i++) { if (p[i].status == 1 && p[i].status == 1) { $scope.productQuantityMultiArray.push({ v_key: p[i].variant_key, v_name: p[i].option_name_array[0], v_qty: 1, v_active: 0 }); } } console.log("iufthsgsdkhfgsdkfjhd :", $scope.productQuantityMultiArray); }; $scope.switchQuantityByKey = function(variant_key) { $scope.lastCheckedVariantKey = variant_key; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price[variant-key!="' + variant_key + '"]').removeClass('active').removeClass('inin'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('active'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('active'); $timeout(function() { // $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('inin'); }, 300); }; $scope.viewQuantity = function() { var check_num = 1; if($(".d_qty.inin").find('select').val() != undefined && $(".d_qty.inin").find('select').val() != ''){ check_num = $(".d_qty.inin").find('select').val().substr(7); }else{ $(".d_qty.inin").find('select').val("number:1"); $(".d_qty.inin").find('select').selectedIndex = "2"; } console.log("shdgshdgsh :",check_num); return parseInt(check_num); }; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; }; $scope.outofstock = 0; $scope.getOutofstock = function() { $scope.outofstock = 1; }; }; return promise; }); _ui_share_app.directive('productDetailPageMa', function($rootScope, $routeParams, sliderProvider ) { var templateName = 'productDetailPageMa'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', fontcolor: '@fontcolor', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window , $location) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataTag = false; $scope._dataArray = []; // $scope.product_sku = ""; // $scope.product_code = ""; // $scope.product_price = 0; // $scope.product_compare_price = 0; $scope._dataArrayState = { load: true, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'txt_product_id': id, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope.dataPreserve = res.data; // $scope.product_sku = res.data.product_sku; // $scope.product_code = res.data.product_code; $scope.product_price = $scope.calculate(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); if ($scope._dataArray.product_referral_display.category != 'undefined' && $scope._dataArray.product_referral_display.category != null) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } if(res.data.product_tags != "" && res.data.product_tags != undefined){ $scope.dataTag = res.data.product_tags.split(","); } if (res.data.product_attribute.length != 0) { if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { // alert("x๊อบไข่สด"); var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ", $scope.data_min); $scope.buildVariantOption(res.data); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } $scope.qtyCurrentSize(res.data.product_total_variant, res.data.product_total_stock); // $scope.buildVariantOption(res.data); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.mkCarousel = function(elem) { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { slidesToShow: 1, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.redirectCheckout = function(p,q){ window.location.href = GURL.base_url() + "checkout?pdata="+p+'-'+q; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var dataSend = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', dataSend).then(function(res) { if (res.ok == 1) { $scope.dataRelation = res.data; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getIdUrl = function() { var getData = []; var returnData = ''; if (typeof $routeParams.product_id !== 'undefined') { getData = $routeParams.product_id; returnData = getData.split("-"); return returnData[0]; } }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleStatres.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleStatres.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.qtyCurrentSize = function(product_total_variant, product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : product_total_variant : ", product_total_variant, "product_total_stock : ", product_total_stock); if (product_total_variant == 0) { if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < parseInt(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock < 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock == 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else { $scope.qty_current_size_state = false; $scope.buy_state = false; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_variant > 0) { if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < product_total_stock; i++) { $scope.qty_current_size.push(i + 1); } } } $scope.qtyShow($scope.qty_current_size); }; $scope.htmlSelectTime = 0; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } } $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").val() == undefined) { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); check_int = 1; } else if ($(".d_qty").val() == "? number:1 ?") { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); } else { check_int = parseInt($(".d_qty").val()); $(".d_qty").val(check_int); } return check_int; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems option_id:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems dataVariantsPick:", $scope.dataVariantsPick); if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.onClickVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); console.log("dataVariants :", dataVariants); var count = 0; if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope.viewInfo = 1; $scope.view = function(input) { $scope.viewInfo = input; } $scope._getDataArray($scope._getIdUrl()); }; return promise; });_ui_share_app.directive('productDetailPageMaeju', function($rootScope, $routeParams, $location, sliderProvider) { var templateName = 'productDetailPageMaeju'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', icon: '@icon', stylebutton: '@stylebutton' }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayTags = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.showTab = { activeTab: 'description', dataTab: [{ en: 'description', th: 'รายละเอียดสินค้า', data: '' }, { en: 'info', th: 'วิธีการชำระเงินและวิธีการจัดส่ง', data: '' }] }; $scope.attribute = { state: false, attributeOption: [], variants: 'description', variantsPick: [], dataVariants: [], variantsTotal: 0 }; $scope.buy = { state: false, attribute: false }; $scope.processBuy = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, onClickFalse: function() { if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } } } return functionIn; }; $scope.attributeOption = function() { var functionIn = { consoleLog: function(name, data) { console.log("productDetailPageMaeju : ", name, data); }, checkVariantsPick: function(variantsPick) { if (variantsPick.length != 0) { var state = 0; for (var i = 0; i < variantsPick.length; i++) { if (variantsPick[i] == "") { state = state + 1; } } if (state == 0) { return true } else { return false } } else { return false } }, compareArray: function(attributeOption, optionJson) { if (!optionJson) return false; if (attributeOption.length != optionJson.length) return false; for (var i = 0, l = attributeOption.length; i < l; i++) { if (attributeOption[i] instanceof Array && optionJson[i] instanceof Array) { if (!compareArray(attributeOption[i], optionJson[i])) return false; } else if (attributeOption[i] != optionJson[i]) { return false; } } return true; }, checkAttributeOption: function(attributeOption, attributeOptionLength, callback) { var _self = this; var attribute = (attributeOption.length == attributeOptionLength) ? true : false; for (var i = 0; i < attributeOption.length; i++) { _self.consoleLog("checkAttributeOption : attributeOption[i] : ", attributeOption[i]); if (attributeOption[i] == undefined) { attribute = false; } } callback(attribute); }, findVariantsData: function(attributeOption, dataVariants, attributeOptionLength, callback) { var _self = this; _self.consoleLog("findVariantsData : attributeOption : ", attributeOption); _self.consoleLog("findVariantsData : dataVariants : ", dataVariants); _self.consoleLog("findVariantsData : attributeOptionLength : ", attributeOptionLength); _self.checkAttributeOption(attributeOption, attributeOptionLength, function(res_attribute_option) { _self.consoleLog("checkAttributeOption : callback : res_attribute_option ", res_attribute_option); var variantsOut = []; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (_self.compareArray(attributeOption, optionJson)) { _self.consoleLog("findVariantsData : dataVariants[i] : ", dataVariants[i]); variantsOut = dataVariants[i]; break; } } callback(variantsOut, res_attribute_option); }); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var _self = this; var state = true; _self.consoleLog("checkTotalStock : index : ", stateIn); _self.consoleLog("checkTotalStock : quantity_max : ", quantity_max); if (stateIn == false && quantity_max > 0) { state = false; } callback(state); }, onClickOption: function($index, option_id) { var _self = this; _self.consoleLog("onClickOption : index : ", $index); _self.consoleLog("onClickOption : option_id : ", option_id); $scope.attribute.variantsPick[$index] = option_id; _self.consoleLog("onClickOption : $scope.attribute.variantsPick[$index] : ", $scope.attribute.variantsPick[$index]); if ($scope.attribute.attributeOption.length >= $scope.attribute.variantsPick.length) { if (_self.checkVariantsPick($scope.attribute.variantsPick)) { _self.consoleLog("onClickOption : if : $scope.attribute.attributeOption.length : ", $scope.attribute.attributeOption.length); _self.consoleLog("onClickOption : if : $scope.attribute.variantsPick.length : ", $scope.attribute.variantsPick.length); _self.findVariantsData($scope.attribute.variantsPick, $scope.attribute.dataVariants, $scope.attribute.attributeOption.length, function(variantsOut, res_attribute_option) { _self.consoleLog("onClickOption : if : findVariantsData : variantsOut : ", variantsOut); _self.consoleLog("onClickOption : if : findVariantsData : res_attribute_option : ", res_attribute_option); if (variantsOut.length != 0 && res_attribute_option) { $scope.dataArray.product_id = variantsOut.product_id; $scope.dataArray.product_sku = variantsOut.sku; $scope.dataProductBuy.price = variantsOut.price; $scope.dataArray.product_compare_price = variantsOut.compare_price; $scope.dataProductBuy.quantity_max = variantsOut.total_stock; if (variantsOut.variant_image != 0) { if ($scope.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataArray.product_image.length; i++) { $scope.dataArray.product_image[i].image_id if ($scope.dataArray.product_image[i].image_id == variantsOut.variant_image[0].image_id) { $scope.slickImageGoto(i); } } } } _self.checkOption($scope.attribute.variantsTotal, function(state) { _self.checkTotalStock(state, variantsOut.total_stock, function(state) { $scope.buy.state = state; if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } }); }); } else if (variantsOut.length == 0 && res_attribute_option) { $scope.dataArray.product_id = 0; $scope.dataArray.product_sku = ''; $scope.dataProductBuy.price = 0; $scope.dataArray.product_compare_price = 0; $scope.dataProductBuy.quantity_max = 1; $scope.buy.state = true; $scope.buy.attribute = true; } $scope.quantity().input(); }); } } } } return functionIn; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity_max; } _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } } } return quantity; }; $scope.carouselId = ''; $scope.slickCarouselId = function() { if ($scope.carouselId == '') { $scope.carouselId = Math.floor((Math.random() * 9999) + 1000); return $scope.carouselId; } else { return $scope.carouselId; } }; $scope.slickImageGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope.carouselId + '"]').slick('slickGoTo', idx); }, 100); }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 100); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log('productDetailPageMaeju : ', name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; product_referral_display.category = (product_referral_display.category != '' && product_referral_display.category != undefined) ? product_referral_display.category : []; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getQuantityBreak: function(api, callback) { var _self = this; _self.getProductId(function(product_id) { var customerId = 0; if (UiCustomerBox.delegate.get.isLogin()) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); } var dataSendQuantityBreak = { 'txt_product_id': product_id, 'txt_customer_id': customerId }; var quantity_break = []; _self.getDataArray(api, dataSendQuantityBreak, function(output) { if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); }); }, quantity: function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.dataArray, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } }, showTab: function(input, callback) { var description = input.product_description; var info = input.product_more_info; callback(description, info); }, productTab: function(product_tags, callback) { var _self = this; _self.consoleLog("productTab : product_tags : ", product_tags); var productTab = []; if (product_tags != undefined) { if (product_tags != "") { productTab = product_tags.split(","); callback(productTab); } else { callback(productTab); } } else { callback(productTab); } }, getAttribute: function(input, callback) { var _self = this; var attribute = []; var variants = []; var variants_total = 0; _self.consoleLog("getAttribute : input : ", input); if (input.product_attribute.option_data !== 'undefined' && input.product_total_variant > 0) { _self.consoleLog("getAttribute : input.product_attribute.option_data : ", input.product_attribute.option_data); _self.consoleLog("getAttribute : input.product_total_variant : ", input.product_total_variant); if (input.product_attribute.option_data.pclass_array !== 'undefined' && input.product_attribute.option_data.pclass_array.length) { _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array : ", input.product_attribute.option_data.pclass_array); _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array.length : ", input.product_attribute.option_data.pclass_array.length); attribute = input.product_attribute.option_data.pclass_array; variants = input.product_attribute.option_data.variant_array; variants_total = input.product_total_variant; } } callback(variants_total, attribute, variants); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = true; if (stateIn == true && quantity_max > 0) { state = false; } callback(state); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, main: function() { var _self = this; $scope.slickCarouselId(); $scope.referralMapState = _self.stateData(true, false); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; _self.dataSend('referral/map', dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { $scope.referralMap = output.data; $scope.referralMapState = _self.stateData(false, true); }); }); $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { if (output.data.length != 0) { _self.consoleLog(" : output : ", output.data); _self.quantity(output.data.product_total_stock, function(total_stock) { _self.consoleLog("quantity : total_stock : ", total_stock); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataArray = output.data; _self.productTab(output.data.product_tags, function(productTab) { $scope.dataArrayTags = productTab; _self.showTab(output.data, function(description, info) { $scope.showTab.dataTab[0].data = description; $scope.showTab.dataTab[1].data = info; }); _self.getAttribute(output.data, function(variants_total, attribute, variants) { _self.consoleLog("getAttribute : variants_total : ", variants_total); _self.consoleLog("getAttribute : attribute : ", attribute); _self.consoleLog("getAttribute : variants : ", variants); _self.checkOption(variants_total, function(state) { _self.checkTotalStock(state, total_stock, function(state) { $scope.buy.state = state; $scope.attribute.attributeOption = attribute; $scope.attribute.dataVariants = variants; $scope.attribute.variantsTotal = variants_total; if (variants_total > 0) { _self.checkPriceMin(variants, function(res_price, res_compare_price) { $scope.dataProductBuy.price = res_price; $scope.dataProductBuy.sumprice = res_price; $scope.dataArray.product_compare_price = res_compare_price; }); } else { $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; } }); }); }); _self.getQuantityBreak('product/quantity_break', function(quantity_break) { _self.consoleLog("getQuantityBreak : output : ", quantity_break); $scope.dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.dataProductBuy.result_price = quantity_break[0].unit_price; } }); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; $scope.dataArrayState = _self.stateData(false, true); }); }); }); } else { window.history.back(); } }); } } return data; }; $scope.getDataArray().main(); $scope.tab_id = 0; $scope.tabId = function(id) { $scope.tab_id = id; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.categoriesData = $scope.routeParams().referral_id || ''; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.checkPrice = function(price) { var check_price = 0; var _price = (price != undefined && price != "" && price != null) ? price.toString() : "0"; if (_price.includes(".")) { check_price = 2; } return check_price; }; }; return promise; });_ui_share_app.directive('productDetailPageMb', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageMb'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', datafont: '@datafont', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $location) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataTag = false; $scope._dataArray = []; $scope.data_min = ""; $scope.data_video_id = false; // $scope.product_sku = ""; // $scope.product_code = ""; // $scope.product_price = 0; // $scope.product_compare_price = 0; $scope._dataArrayState = { load: true, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'txt_product_id': id, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/id', dataSend, $scope).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope.dataPreserve = res.data; $scope.data_video_id = res.data.product_id; // $scope.product_sku = res.data.product_sku; // $scope.product_code = res.data.product_code; $scope.product_price = $scope.calculate(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); if ($scope._dataArray.product_referral_display.category != 'undefined' && $scope._dataArray.product_referral_display.category != null) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.dataTag = res.data.product_tags.split(","); if (res.data.product_attribute.length != 0) { if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { // alert("x๊อบไข่สด"); var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ", $scope.data_min); $scope.buildVariantOption(res.data); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } /*$scope.sale($scope._dataArray.product_price, $scope._dataArray.product_compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); */ $scope.qtyCurrentSize(res.data.product_total_variant, res.data.product_total_stock); // $scope.buildVariantOption(res.data); } var t = $interval(function() { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function() { $timeout.cancel(tt); $scope.mkCarousel(); }, 300); } }, 500); $scope._dataArrayState = $scope.StateData(false, true); }); }; $rootScope.$on('repeatend', function() { /* Check Lightbox Enable/Disable */ $('a[data-photo-index]').each(function(idx, obj) { $(this).attr('data-lightbox', 'view-gallery'); }); }); $scope.mkCarousel = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, centerMode: true, centerPadding: '0px', slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: true, infinite: true, /*prevArrow: '', nextArrow: '',*/ responsive: [{ breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 1 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 1 } }] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.redirectCheckout = function(p, q) { window.location.href = GURL.base_url() + "checkout?pdata=" + p + '-' + q; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var dataSend = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', dataSend).then(function(res) { if (res.ok == 1) { $scope.dataRelation = res.data; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getIdUrl = function() { var getData = []; var returnData = ''; if (typeof $routeParams.product_id !== 'undefined') { getData = $routeParams.product_id; returnData = getData.split("-"); return returnData[0]; } }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } /* alert(price); */ return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.qtyCurrentSize = function(product_total_variant, product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : product_total_variant : ", product_total_variant, "product_total_stock : ", product_total_stock); if (product_total_variant == 0) { if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < parseInt(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock < 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock == 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else { $scope.qty_current_size_state = false; $scope.buy_state = false; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_variant > 0) { if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < product_total_stock; i++) { $scope.qty_current_size.push(i + 1); } } } $scope.qtyShow($scope.qty_current_size); }; $scope.htmlSelectTime = 0; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } } $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").val() == undefined) { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); check_int = 1; } else if ($(".d_qty").val() == "? number:1 ?") { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); } else { check_int = parseInt($(".d_qty").val()); $(".d_qty").val(check_int); } return check_int; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } console.log("buildVariantOption objectData : ", objectData); $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; if ($scope.dataOption.length == 1) { console.log("buildVariantOption objectData.length : ", $scope.dataOption.length); setTimeout(function() { $scope.totalStock($scope.dataOption.length, $scope.dataVariants, 0, 0); }, 1000); } $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems option_id:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems dataVariantsPick:", $scope.dataVariantsPick); if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.displayView = function(id, statusClass, status) { var option; if (id != "0") { option = $('.text_4.variantSelector .t_2 .items' + '[data-option=' + id + ']'); } else { option = $('.text_4.variantSelector .t_2 .items'); } if (statusClass == 'add') { if (!option.hasClass(status)) { option.addClass(status); } } else if (statusClass == 'remove') { if (option.hasClass(status)) { option.removeClass(status); } } else if (statusClass == 'reset') { if (option.hasClass(status)) { option.removeClass(status); } } }; $scope.totalStock = function(dataVariantsPickLength, dataVariants, $index, option_id) { console.log("totalStock : dataVariantsPickLength : ", dataVariantsPickLength); console.log("totalStock : dataVariants : ", dataVariants); console.log("totalStock : $index : ", $index, " option_id : ", option_id); var dataVariants = $scope.dataVariants; $scope.displayView('0', 'reset', 'zero'); for (var i = 0; i < dataVariants.length; i++) { var array_option_id = angular.fromJson(dataVariants[i].option_id_json); console.log("totalStock : for : array_option_id : ", array_option_id); console.log("totalStock : for : dataVariantsPickLength : ", dataVariantsPickLength); if (dataVariantsPickLength > 1) { if (array_option_id[$index] == option_id) { /* console.log("totalStock : for : if : array_option_id[", $index, "]", array_option_id[$index]); */ console.log("totalStock : for : if : if : array_option_id : ", array_option_id); console.log("totalStock : for : if : if : dataVariants : [", i, "] :", dataVariants[i]); for (var j = 0; j < array_option_id.length; j++) { if (j != $index && dataVariants[i].total_stock == 0) { $scope.displayView(array_option_id[j], 'add', 'zero'); } else { $scope.displayView(array_option_id[j], 'remove', 'zero'); } } } } else { /* console.log("totalStock : for : if : array_option_id[", $index, "]", array_option_id[$index]); */ console.log("totalStock : for : else : if : array_option_id : ", array_option_id); console.log("totalStock : for : else : if : dataVariants : [", i, "] :", dataVariants[i]); for (var j = 0; j < array_option_id.length; j++) { console.log("totalStock : for : else : if : dataVariants : [", i, "] :", dataVariants[i].total_stock); if (dataVariants[i].total_stock == 0) { $scope.displayView(array_option_id[j], 'add', 'zero'); } else { $scope.displayView(array_option_id[j], 'remove', 'zero'); } } } } }; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems : ", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems : dataVariantsPick.length : ", $scope.dataVariantsPick.length); console.log("onSelectVariantItems : dataOption.length : ", $scope.dataOption.length); console.log("onSelectVariantItems : dataVariantsPick : ", $scope.dataVariantsPick); console.log("onSelectVariantItems : dataOption : ", $scope.dataOption); $scope.totalStock($scope.dataVariantsPick.length, $scope.dataVariants, $index, option_id); if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { console.log("findVariantsData : variantsPick : ", variantsPick); function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; console.log("findVariantsData : dataVariants : ", dataVariants); for (var i = 0; i < dataVariants.length; i++) { console.log("findVariantsData : for : dataVariants[", i, "] :", dataVariants[i]); var _self = dataVariants[i]; var optionJson = angular.fromJson(dataVariants[i].option_id_json); console.log("findVariantsData : for : optionJson[", i, "].option_id_json :", angular.fromJson(dataVariants[i].option_id_json)); var count = 0; if (compareArray(variantsPick, optionJson)) { console.log("findVariantsData : compareArray : ", compareArray(variantsPick, optionJson)); console.log("findVariantsData : for : if : dataVariants[", i, "] :", dataVariants[i]); $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope._dataArray.product_image.length; im++) { if ($scope._dataArray.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } $timeout(function() { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { // $scope._slickGoto('gallery_show', rightImagePosition); } else { angular.element('.block-gallery .thumb-img[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300); } break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope.viewInfo = 1; $scope.view = function(input) { $scope.viewInfo = input; } $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope.switchSingleView = function(idx) { console.log("$xZoomInstance", $xZoomInstance); $('.gallery_show_single').css({ 'transition': 'all 0.3s', 'opacity': '0' }); $timeout(function() { $scope.gallerySingleViewIndex = idx; $('.gallery_show_single').css({ 'opacity': '1' }); }, 300); setTimeout(function() { if ($(window).width() >= 992) { if ($("img.zoom").attr('data-api-width') > 400 && $("img.zoom").attr('data-api-height') > 400) { /*$("img.zoom").ezPlus({ 'scrollZoom':true, 'responsive':true, 'zoomWindowWidth':400, 'zoomWindowHeight':400, 'zoomWindowOffetx':30, });*/ $xZoomInstance = $('.zoom').xzoom({ Xoffset: 30, tint: '#b9b5b3', }); } } }, 300); }; $scope.gallerySingleViewIndex = 0; $scope.switchSingleView = function(idx) { console.log("$xZoomInstance", $xZoomInstance); $('.gallery_show_single').css({ 'transition': 'all 0.3s', 'opacity': '0' }); $timeout(function() { $scope.gallerySingleViewIndex = idx; $('.gallery_show_single').css({ 'opacity': '1' }); }, 300); setTimeout(function() { if ($(window).width() >= 992) { if ($("img.zoom").attr('data-api-width') > 400 && $("img.zoom").attr('data-api-height') > 400) { /*$("img.zoom").ezPlus({ 'scrollZoom':true, 'responsive':true, 'zoomWindowWidth':400, 'zoomWindowHeight':400, 'zoomWindowOffetx':30, });*/ $xZoomInstance = $('.zoom').xzoom({ Xoffset: 30, tint: '#b9b5b3', }); } } }, 300); }; $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; $scope._getDataArray($scope._getIdUrl()); }; return promise; });_ui_share_app.directive('productDetailPageMc', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageMc'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', icon: '@icon', stylebutton: '@stylebutton' }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayTags = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.showTab = { activeTab: 'description', dataTab: [{ en: 'description', th: 'รายละเอียดสินค้า', data: '' }, { en: 'info', th: 'วิธีการชำระเงินและวิธีการจัดส่ง', data: '' }] }; $scope.attribute = { state: false, attributeOption: [], variants: 'description', variantsPick: [], dataVariants: [], variantsTotal: 0 }; $scope.buy = { state: false, attribute: false }; $scope.processBuy = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, onClickFalse: function() { if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } } } return functionIn; }; $scope.attributeOption = function() { var functionIn = { consoleLog: function(name, data) { console.log("productDetailPageMaeju : ", name, data); }, checkVariantsPick: function(variantsPick) { if (variantsPick.length != 0) { var state = 0; for (var i = 0; i < variantsPick.length; i++) { if (variantsPick[i] == "") { state = state + 1; } } if (state == 0) { return true } else { return false } } else { return false } }, compareArray: function(attributeOption, optionJson) { if (!optionJson) return false; if (attributeOption.length != optionJson.length) return false; for (var i = 0, l = attributeOption.length; i < l; i++) { if (attributeOption[i] instanceof Array && optionJson[i] instanceof Array) { if (!compareArray(attributeOption[i], optionJson[i])) return false; } else if (attributeOption[i] != optionJson[i]) { return false; } } return true; }, checkAttributeOption: function(attributeOption, attributeOptionLength, callback) { var _self = this; var attribute = (attributeOption.length == attributeOptionLength) ? true : false; for (var i = 0; i < attributeOption.length; i++) { _self.consoleLog("checkAttributeOption : attributeOption[i] : ", attributeOption[i]); if (attributeOption[i] == undefined) { attribute = false; } } callback(attribute); }, findVariantsData: function(attributeOption, dataVariants, attributeOptionLength, callback) { var _self = this; _self.consoleLog("findVariantsData : attributeOption : ", attributeOption); _self.consoleLog("findVariantsData : dataVariants : ", dataVariants); _self.consoleLog("findVariantsData : attributeOptionLength : ", attributeOptionLength); _self.checkAttributeOption(attributeOption, attributeOptionLength, function(res_attribute_option) { _self.consoleLog("checkAttributeOption : callback : res_attribute_option ", res_attribute_option); var variantsOut = []; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (_self.compareArray(attributeOption, optionJson)) { _self.consoleLog("findVariantsData : dataVariants[i] : ", dataVariants[i]); variantsOut = dataVariants[i]; break; } } callback(variantsOut, res_attribute_option); }); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var _self = this; var state = true; _self.consoleLog("checkTotalStock : index : ", stateIn); _self.consoleLog("checkTotalStock : quantity_max : ", quantity_max); if (stateIn == false && quantity_max > 0) { state = false; } callback(state); }, onClickOption: function($index, option_id) { var _self = this; _self.consoleLog("onClickOption : index : ", $index); _self.consoleLog("onClickOption : option_id : ", option_id); $scope.attribute.variantsPick[$index] = option_id; _self.consoleLog("onClickOption : $scope.attribute.variantsPick[$index] : ", $scope.attribute.variantsPick[$index]); if ($scope.attribute.attributeOption.length >= $scope.attribute.variantsPick.length) { if (_self.checkVariantsPick($scope.attribute.variantsPick)) { _self.consoleLog("onClickOption : if : $scope.attribute.attributeOption.length : ", $scope.attribute.attributeOption.length); _self.consoleLog("onClickOption : if : $scope.attribute.variantsPick.length : ", $scope.attribute.variantsPick.length); _self.findVariantsData($scope.attribute.variantsPick, $scope.attribute.dataVariants, $scope.attribute.attributeOption.length, function(variantsOut, res_attribute_option) { _self.consoleLog("onClickOption : if : findVariantsData : variantsOut : ", variantsOut); _self.consoleLog("onClickOption : if : findVariantsData : res_attribute_option : ", res_attribute_option); if (variantsOut.length != 0 && res_attribute_option) { $scope.dataArray.product_id = variantsOut.product_id; $scope.dataArray.product_sku = variantsOut.sku; $scope.dataProductBuy.price = variantsOut.price; $scope.dataArray.product_compare_price = variantsOut.compare_price; $scope.dataProductBuy.quantity_max = variantsOut.total_stock; if (variantsOut.variant_image != 0) { if ($scope.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataArray.product_image.length; i++) { $scope.dataArray.product_image[i].image_id if ($scope.dataArray.product_image[i].image_id == variantsOut.variant_image[0].image_id) { $scope.slickImageGoto(i); } } } } _self.checkOption($scope.attribute.variantsTotal, function(state) { _self.checkTotalStock(state, variantsOut.total_stock, function(state) { $scope.buy.state = state; if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } }); }); } else if (variantsOut.length == 0 && res_attribute_option) { $scope.dataArray.product_id = 0; $scope.dataArray.product_sku = ''; $scope.dataProductBuy.price = 0; $scope.dataArray.product_compare_price = 0; $scope.dataProductBuy.quantity_max = 1; $scope.buy.state = true; $scope.buy.attribute = true; } $scope.quantity().input(); }); } } } } return functionIn; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity_max; } _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } } } return quantity; }; $scope.carouselId = ''; $scope.slickCarouselId = function() { if ($scope.carouselId == '') { $scope.carouselId = Math.floor((Math.random() * 9999) + 1000); return $scope.carouselId; } else { return $scope.carouselId; } }; $scope.slickImageGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope.carouselId + '"]').slick('slickGoTo', idx); }, 100); }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 100); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log('productDetailPageMaeju : ', name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getQuantityBreak: function(api, callback) { var _self = this; _self.getProductId(function(product_id) { var customerId = 0; if (UiCustomerBox.delegate.get.isLogin()) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); } var dataSendQuantityBreak = { 'txt_product_id': product_id, 'txt_customer_id': customerId }; var quantity_break = []; _self.getDataArray(api, dataSendQuantityBreak, function(output) { if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); }); }, quantity: function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.dataArray, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } }, showTab: function(input, callback) { var description = input.product_description; var info = input.product_more_info; callback(description, info); }, productTab: function(product_tags, callback) { var _self = this; _self.consoleLog("productTab : product_tags : ", product_tags); var productTab = []; if (product_tags != undefined) { if (product_tags != "") { productTab = product_tags.split(","); callback(productTab); } else { callback(productTab); } } else { callback(productTab); } }, getAttribute: function(input, callback) { var _self = this; var attribute = []; var variants = []; var variants_total = 0; _self.consoleLog("getAttribute : input : ", input); if (input.product_attribute.option_data !== 'undefined' && input.product_total_variant > 0) { _self.consoleLog("getAttribute : input.product_attribute.option_data : ", input.product_attribute.option_data); _self.consoleLog("getAttribute : input.product_total_variant : ", input.product_total_variant); if (input.product_attribute.option_data.pclass_array !== 'undefined' && input.product_attribute.option_data.pclass_array.length) { _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array : ", input.product_attribute.option_data.pclass_array); _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array.length : ", input.product_attribute.option_data.pclass_array.length); attribute = input.product_attribute.option_data.pclass_array; variants = input.product_attribute.option_data.variant_array; variants_total = input.product_total_variant; } } callback(variants_total, attribute, variants); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = true; if (stateIn == true && quantity_max > 0) { state = false; } callback(state); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, main: function() { var _self = this; $scope.slickCarouselId(); $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { if (output.data.length != 0) { _self.consoleLog(" : output : ", output.data); _self.quantity(output.data.product_total_stock, function(total_stock) { _self.consoleLog("quantity : total_stock : ", total_stock); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataArray = output.data; _self.productTab(output.data.product_tags, function(productTab) { $scope.dataArrayTags = productTab; _self.showTab(output.data, function(description, info) { $scope.showTab.dataTab[0].data = description; $scope.showTab.dataTab[1].data = info; }); _self.getAttribute(output.data, function(variants_total, attribute, variants) { _self.consoleLog("getAttribute : variants_total : ", variants_total); _self.consoleLog("getAttribute : attribute : ", attribute); _self.consoleLog("getAttribute : variants : ", variants); _self.checkOption(variants_total, function(state) { _self.checkTotalStock(state, total_stock, function(state) { $scope.buy.state = state; $scope.attribute.attributeOption = attribute; $scope.attribute.dataVariants = variants; $scope.attribute.variantsTotal = variants_total; if (variants_total > 0) { _self.checkPriceMin(variants, function(res_price, res_compare_price) { $scope.dataProductBuy.price = res_price; $scope.dataProductBuy.sumprice = res_price; $scope.dataArray.product_compare_price = res_compare_price; }); } else { $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; } }); }); }); _self.getQuantityBreak('product/quantity_break', function(quantity_break) { _self.consoleLog("getQuantityBreak : output : ", quantity_break); $scope.dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.dataProductBuy.result_price = quantity_break[0].unit_price; } }); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; $scope.dataArrayState = _self.stateData(false, true); }); }); }); } else { window.history.back(); } }); } } return data; }; $scope.getDataArray().main(); $scope.tab_id = 0; $scope.tabId = function(id) { $scope.tab_id = id; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.categoriesData = $scope.routeParams().referral_id || ''; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.checkPrice = function(price) { var check_price = 0; var _price = (price != undefined && price != "" && price != null) ? price.toString() : "0"; if (_price.includes(".")) { check_price = 2; } return check_price; }; }; return promise; });_ui_share_app.directive('productDetailPageMhp', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageMhp'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayTags = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.showTab = { activeTab: 'description', dataTab: [{ en: 'description', th: 'รายละเอียดสินค้า', data: '' }, { en: 'info', th: 'วิธีการชำระเงินและวิธีการจัดส่ง', data: '' }] }; $scope.attribute = { state: false, attributeOption: [], variants: 'description', variantsPick: [], dataVariants: [], variantsTotal: 0 }; $scope.buy = { state: false, attribute: false }; $scope.processBuy = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, onClickFalse: function() { if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } } } return functionIn; }; $scope.attributeOption = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, checkVariantsPick: function(variantsPick) { if (variantsPick.length != 0) { var state = 0; for (var i = 0; i < variantsPick.length; i++) { if (variantsPick[i] == "") { state = state + 1; } } if (state == 0) { return true } else { return false } } else { return false } }, compareArray: function(attributeOption, optionJson) { if (!optionJson) return false; if (attributeOption.length != optionJson.length) return false; for (var i = 0, l = attributeOption.length; i < l; i++) { if (attributeOption[i] instanceof Array && optionJson[i] instanceof Array) { if (!compareArray(attributeOption[i], optionJson[i])) return false; } else if (attributeOption[i] != optionJson[i]) { return false; } } return true; }, findVariantsData: function(attributeOption, dataVariants, callback) { var _self = this; var variants = dataVariants; _self.consoleLog("findVariantsData : variants : ", variants); var variantsOut = []; for (var i = 0; i < variants.length; i++) { var optionJson = angular.fromJson(variants[i].option_id_json); if (_self.compareArray(attributeOption, optionJson)) { _self.consoleLog("findVariantsData : variants[i] : ", variants[i]); variantsOut = variants[i]; break; } } callback(variantsOut); }, checkOption: function(variants_total, callback) { var state = false; if (variants_total == 0) { state = true; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = false; if (stateIn == false && quantity_max > 0) { state = true; } callback(state); }, onClickOption: function($index, option_id) { var _self = this; _self.consoleLog("onClickOption : index : ", $index); _self.consoleLog("onClickOption : option_id : ", option_id); $scope.attribute.variantsPick[$index] = option_id; _self.consoleLog("onClickOption : $scope.attribute.variantsPick[$index] : ", $scope.attribute.variantsPick[$index]); if ($scope.attribute.attributeOption.length >= $scope.attribute.variantsPick.length) { if (_self.checkVariantsPick($scope.attribute.variantsPick)) { _self.consoleLog("onClickOption : if : $scope.attribute.attributeOption.length : ", $scope.attribute.attributeOption.length); _self.consoleLog("onClickOption : if : $scope.attribute.variantsPick.length : ", $scope.attribute.variantsPick.length); _self.findVariantsData($scope.attribute.variantsPick, $scope.attribute.dataVariants, function(variantsOut) { _self.consoleLog("onClickOption : if : findVariantsData : variantsOut : ", variantsOut); $scope.dataArray.product_id = variantsOut.product_id; $scope.dataArray.product_sku = variantsOut.sku; $scope.dataArray.product_price = variantsOut.price; $scope.dataArray.product_compare_price = variantsOut.compare_price; $scope.dataProductBuy.quantity_max = variantsOut.total_stock; _self.checkOption($scope.attribute.variantsTotal, function(state) { _self.checkTotalStock(state, variantsOut.total_stock, function(state) { $scope.buy.state = state; if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } }); }); $scope.quantity().input(); }); } } } } return functionIn; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity_max; } _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } } } return quantity; }; $scope.carouselId = ''; $scope.slickCarouselId = function() { if ($scope.carouselId == '') { $scope.carouselId = Math.floor((Math.random() * 9999) + 1000); return $scope.carouselId; } else { return $scope.carouselId; } }; $scope.slickImageGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope.carouselId + '"]').slick('slickGoTo', idx); }, 100); }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 1000); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log(name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getQuantityBreak: function(api, callback) { var _self = this; _self.getProductId(function(product_id) { var customerId = 0; if (UiCustomerBox.delegate.get.isLogin()) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); } var dataSendQuantityBreak = { 'txt_product_id': product_id, 'txt_customer_id': customerId }; var quantity_break = []; _self.getDataArray(api, dataSendQuantityBreak, function(output) { if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); }); }, quantity: function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 999; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.dataArray, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } }, showTab: function(input, callback) { var description = input.product_description; var info = input.product_more_info; callback(description, info); }, productTab: function(product_tags, callback) { var _self = this; _self.consoleLog("productTab : product_tags : ", product_tags); var productTab = []; if (product_tags != undefined) { if (product_tags != "") { productTab = product_tags.split(","); callback(productTab); } else { callback(productTab); } } else { callback(productTab); } }, getAttribute: function(input, callback) { var _self = this; var attribute = []; var variants = []; var variants_total = 0; _self.consoleLog("getAttribute : input : ", input); if (input.product_attribute.option_data !== 'undefined' && input.product_total_variant > 0) { _self.consoleLog("getAttribute : input.product_attribute.option_data : ", input.product_attribute.option_data); _self.consoleLog("getAttribute : input.product_total_variant : ", input.product_total_variant); if (input.product_attribute.option_data.pclass_array !== 'undefined' && input.product_attribute.option_data.pclass_array.length) { _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array : ", input.product_attribute.option_data.pclass_array); _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array.length : ", input.product_attribute.option_data.pclass_array.length); attribute = input.product_attribute.option_data.pclass_array; variants = input.product_attribute.option_data.variant_array; variants_total = input.product_total_variant; } } callback(variants_total, attribute, variants); }, checkOption: function(variants_total, callback) { var state = false; if (variants_total == 0) { state = true; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = false; if (stateIn == true && quantity_max > 0) { state = true; } callback(state); }, main: function() { var _self = this; $scope.slickCarouselId(); $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { _self.consoleLog("getDataProductArray : output : ", output.data); _self.quantity(output.data.product_total_stock, function(total_stock) { _self.consoleLog("quantity : total_stock : ", total_stock); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataArray = output.data; _self.productTab(output.data.product_tags, function(productTab) { $scope.dataArrayTags = productTab; _self.showTab(output.data, function(description, info) { $scope.showTab.dataTab[0].data = description; $scope.showTab.dataTab[1].data = info; }); _self.getAttribute(output.data, function(variants_total, attribute, variants) { _self.consoleLog("getAttribute : variants_total : ", variants_total); _self.consoleLog("getAttribute : attribute : ", attribute); _self.consoleLog("getAttribute : variants : ", variants); _self.checkOption(variants_total, function(state) { _self.checkTotalStock(state, total_stock, function(state) { $scope.buy.state = state; $scope.attribute.attributeOption = attribute; $scope.attribute.dataVariants = variants; $scope.attribute.variantsTotal = variants_total; }); }); }); $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; _self.getQuantityBreak('product/quantity_break', function(quantity_break) { _self.consoleLog("getQuantityBreak : output : ", quantity_break); $scope.dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.dataProductBuy.result_price = quantity_break[0].unit_price; } }); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; $scope.dataArrayState = _self.stateData(false, true); }); }); }); }); } } return data; }; $scope.getDataArray().main(); }; return promise; });_ui_share_app.directive('productDetailPageN', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageN'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', id: '@id', imgcart: '@imgcart', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.qtyProduct = 1; $scope.result_price = 0; $scope.checkQty = function() { var productQuantityBreak = GAEAPI.getValueForKey($scope.data, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); console.log("quantityBreak : ", $scope.data); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.qtyProduct >= amount_end) { $scope.result_price = unit_price; } } }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; /* JQ: Scroll event */ angular.element($window).bind('scroll', function() { if (!$scope.data) { return; } var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos", curPos, properHeight); if (curPos > properHeight) { angular.element('.block-background .bottom-info').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Slider Send */ $scope.data_tag = []; $scope.data = false; $scope.dataPreserve = false; /* Get product id from url or from component */ $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; $scope._dataArrayTags = []; /* getProductId */ $scope.getQuantityBreak = function(dataSend, api, callback) { console.log("getQuantityBreak : dataSend : ", dataSend, " api : ", api); var quantity_break = []; GAEAPI.get(api, dataSend).then(function(output) { console.log("getQuantityBreak : output : ", output); if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); callback(quantity_break); }; $scope.getProductId = function(statusLogin, customerId, dataSend, api) { console.log("getProductId : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); GAEAPI.get(api, dataSend).then(function(output) { console.log("getProductId : output : ", output); if (output.ok == 1) { if (output.data != undefined) { console.log("getProductId : output.data : ", output.data); $scope.data = output.data; $scope.dataPreserve = output.data; /* product_tags */ if (output.data.product_tags != undefined) { if (output.data.product_tags != "") { $scope._dataArrayTags = output.data.product_tags.split(","); /* split(","); */ if ($scope._dataArrayTags == 1 && $scope._dataArrayTags[0] != "") { $scope.data_tag = (output.data.product_tags).split(","); } } } /* product_referral_display */ if (output.data.product_referral_display != undefined) { if (output.data.product_referral_display.length) { $scope._getSupportDataCategory(output.data); } } /* Option */ $scope.buildVariantOption(output.data); /* ProductRelate */ $scope.buildDataProductRelate(dataSend.txt_product_id); /* product_quantity_break */ $scope.checkLogin('product/quantity_break', dataSend.txt_product_id, statusLogin, function(statusLogin, customerId, dataSend, api) { console.log("getProductId checkLogin callback : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); if (statusLogin) { console.log("getProductId checkLogin : IF"); $scope.getQuantityBreak(dataSend, api, function(quantity_break) { console.log("getProductId checkLogin callback getQuantityBreak : quantity_break : ", quantity_break); $scope.data.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.result_price = quantity_break[0].unit_price; } }); } else { console.log("getProductId checkLogin : ELSE") } }); } } }); }; $scope.checkLogin = function(urlApi, product_id, status_login, callback) { var dataSend = {}; var productId = parseInt(product_id); var statusLogin = status_login; var api = urlApi; var customerId = 0; if (api == 'product/id') { dataSend = { 'txt_product_id': productId, } console.log("checkLogin : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); callback(statusLogin, customerId, dataSend, api); } else if (api == 'product/quantity_break') { if (statusLogin) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); dataSend = { 'txt_product_id': productId, 'txt_customer_id': customerId, } console.log("checkLogin : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); callback(statusLogin, customerId, dataSend, api); } else { console.log("checkLogin : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); callback(statusLogin, customerId, dataSend, api); } } }; $scope.checkLogin('product/id', $scope._getPostIdFromURL(), UiCustomerBox.delegate.get.isLogin(), function(statusLogin, customerId, dataSend, api) { console.log("checkLogin callback : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); $scope.getProductId(statusLogin, customerId, dataSend, api); }); /* getProductId */ $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id) { var j = { 'relate_product_id_array': [product_id], 'badge_id_array': [18] }; var d = { 'cur_page': 1, 'per_page': 6, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists', d).then(function(e) { if (e.ok == 1) { $scope.dataRelate = e.data.dataList; console.log("dataRelate", $scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $timeout.cancel(s); $('select.variantSelector').each(function(idx, obj) { var optionElementFirst = $(this).find('option[data-index="' + idx + '"]').eq(0); optionElementFirst.prop("selected", true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original = 1; $scope.qty_current = 1; /* Click SLick Item */ $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; /* Calcu Nav Arrows */ $scope.maxHeight = 0; $scope.navArrowsCalculate = function() { var size = ($('img.img_gallery').eq(0).height() / 2); $scope.maxHeight = (size + 18); $('img.img_gallery').each(function() { if ($(this).height() > $scope.maxHeight) { $scope.maxHeight = $(this).height(); } }); return '-' + $scope.maxHeight + 'px'; }; $scope.navArrowWidth = function() { return $('#gallery_display').width() + 'px'; }; $scope.viewType = 'description'; var selector = '.nav li'; $(selector).on('click', function() { $(selector).removeClass('active'); $(this).addClass('active'); }); $scope.toTop = function() { return window.scrollTo(0, 0); }; $scope._page_lists = false; $scope._page_lists_load = false; $scope._get_page_lists = function() { $scope._clear_page_lists(); var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'page_lastest_create' }; GAEAPI.get('page/lists', dataSend).then(function(res) { $scope._page_lists_load = true; if (res.ok === 1) { $scope._page_lists = res.data.dataList; angular.forEach($scope._page_lists, function(item, key) { if (item.page_search_url == "") { item.page_search_url = item.page_id; } }); } }); }; $scope.support_data = { category: [], }; $scope._getSupportDataCategory = function(data) { console.log("_getSupportDataCategory : data : ", data); console.log("_getSupportDataCategory : data : ", data.product_referral_display); var dataSend = { 'txt_referral_id': data.product_referral_display.category[0].referral_id }; console.log("_getSupportDataCategory : dataSend : ", dataSend); GAEAPI.get('referral/relation', dataSend).then(function(e) { if (e.ok == 1) { $scope.support_data.category = e.data; console.log("dyfsyhfgdhfd :", $scope.support_data.category); } }); }; $scope._clear_page_lists = function() { $scope._page_lists = false; $scope._page_lists_load = false; }; $scope._get_page_lists(); $scope._page_category = false; $scope._page_category_load = false; $scope._get_page_category = function() { $scope._clear_page_lists(); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_name_a-z' }; GAEAPI.get('referral/map', dataSend).then(function(res) { $scope._page_category_load = true; if (res.ok === 1) { $scope._page_category = res.data; } }); }; $scope._clear_page_category = function() { $scope._page_category = false; $scope._page_category_load = false; }; $scope._get_page_category(); $scope._testdata = [{ id: '1', Buy: '1', Price: '699', Discount: '0%' }, { id: '2', Buy: '3', Price: '550', Discount: '10%' }, { id: '3', Buy: '6', Price: '530', Discount: '15%' }, { id: '4', Buy: '12', Price: '520', Discount: '16%' }, { id: '5', Buy: '50', Price: '510', Discount: '17%' }]; $scope._get_page_category(); $scope.mkCarouselData = function(elem) { console.debug('mkCarouselData: trigger'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 5, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1330, settings: { slidesToShow: 5, } }, { breakpoint: 991, settings: { slidesToShow: 5, } }, { breakpoint: 767, settings: { slidesToShow: 5, } }, { breakpoint: 692, settings: { slidesToShow: 6, } }, { breakpoint: 540, settings: { slidesToShow: 3, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope._indata = $scope._testdata[0].id; $scope._indataPrice = $scope._testdata[0].Price; $scope._inputdata = function(data, Price) { $scope._indata = data; $scope._indataPrice = Price; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; }; return promise; });_ui_share_app.directive('productDetailPageP', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageP'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', promotelink: '@promotelink', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; /* JQ: Scroll event */ angular.element($window).bind('scroll', function() { if (!$scope.data) { return; } var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos", curPos, properHeight); if (curPos > properHeight) { angular.element('.block-background .bottom-info').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Slider Send */ $scope.data = false; $scope.dataPreserve = false; $scope._getDataArray = function(id) { var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope.data = res.data; $scope.dataPreserve = res.data; $scope.buildVariantOption(res.data); $scope._getSupportDataCategory('category', res.data); } }); }; $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id) { var j = { 'relate_product_id_array': [product_id], 'badge_id_array': [18] }; var d = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists', d).then(function(e) { if (e.ok == 1) { $scope.dataRelate = e.data.dataList; console.log("dataRelate", $scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $timeout.cancel(s); $('select.variantSelector').each(function(idx, obj) { var optionElementFirst = $(this).find('option[data-index="' + idx + '"]').eq(0); optionElementFirst.prop("selected", true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._makeProductToCarousel(); }, 500); } }); $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.qty_original = 1; $scope.qty_current = 1; $scope.viewImg = 0; $scope.values = [1, 2, 3, 4, 5]; $scope.myOptions = { 1: "1", 2: "2", 3: "3", 4: "4", 5: "5", 6: "6", 7: "7", 8: "8", 9: "9", 10: "10", }; $scope.$watchCollection('myOptions', function() { $scope.myFixedOptions = []; angular.forEach($scope.myOptions, function(value, key) { $scope.myFixedOptions.push({ key: parseInt(key, 10), value: value }); }); }); $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope.support_data = { category: [], }; $scope._getSupportDataCategory = function(type, data) { var dataSend = { 'txt_referral_id': data.product_referral_display.category[0].referral_id }; GAEAPI.get('referral/relation', dataSend).then(function(e) { if (e.ok == 1) { $scope.support_data.category = e.data; } }); }; $scope.productQuantityMultiArray = []; $scope.lastCheckedVariantKey = ''; $scope.buildMultipleQuantity = function(productObj) { $scope.productQuantityMultiArray = []; var r = [], p = productObj.product_attribute.option_data.variant_array; for (var i = 0; i < p.length; i++) { if (p[i].status == 1 && p[i].status == 1) { $scope.productQuantityMultiArray.push({ v_key: p[i].variant_key, v_name: p[i].option_name_array[0], v_qty: 1, v_active: 0 }); } } }; $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); } else { alert("item can't compare"); } } else { var toDel = $scope.invited.indexOf(user.product_id); $scope.invited.splice(toDel, '1'); } }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; $scope._data_qty_selected = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.currentOptionQtyPick = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } return e.val(); }; }; return promise; });_ui_share_app.directive('productDetailPagePi', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPagePi'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataSet = [{ api: "product/id", dataSend: {}, dataArray: [], dataSendState: { load: false, done: false } }, { api: "referral/relation", dataSend: {}, dataArray: [], dataSendState: { load: false, done: false } }]; $scope.dataTab = { active: 0, tabArray: [{ type: 1, name: 'ภาพรวม', state: true, compileDetail: '', compileArray: [] }, { type: 2, name: 'คุณสมบัติเฉพาะทางเทคนิค', state: true, compileDetail: '', compileArray: [] }, { type: 1, name: 'ข้อมูลเพิ่มเติม', state: true, compileDetail: '', compileArray: [] }] }; $scope.getTab = function() { var getFunction = { active: function(active, callback) { callback(active); }, setTab: function(active) { var _self = this; _self.active(parseInt(active), function(active) { $scope.dataTab.active = active; }); }, pullData: function(index, data, callback) { var res_data = (data != '' && data != undefined) ? data : ''; var res_state = (index == 0) ? true : (data != '' && data != undefined) ? true : false; $scope.getFunction().consoleLog(" : ", res_state); callback(index, res_data, res_state); }, pullDataArray: function(index, dataArray, callback) { var res_data_array = []; if (dataArray.length != 0 && dataArray.length != undefined) { if (dataArray.specification_data.length != 0 && dataArray.specification_data.length != undefined) { if (dataArray.specification_data.pclass_array.length != 0 && dataArray.specification_data.pclass_array.length != undefined) { res_data_array = dataArray.specification_data.pclass_array; } } } var res_state = (index == 0) ? true : (dataArray.length != 0 && dataArray != undefined) ? true : false; callback(index, res_data_array, res_state); } } return getFunction; }; $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = "productDetailPagePi : "; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { console.log(component, name, data); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, getRouteParamsProductId: function(callback) { var _self = this; _self.getRouteParams(function(params) { var product_id = params.product_id.split("-", 1).join(""); callback(product_id); }); }, stateData: function(load, done) { var _self = this; _self.consoleLog("stateData : load : ", load); _self.consoleLog("stateData : done : ", done); var state = { load: load, done: done }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend : api : ", api); _self.consoleLog("dataSend : dataSend : ", dataSend); callback(api, dataSend); }, getApiOk: function(res_api, callback) { var _self = this; var res_ok = []; if (res_api.ok == 1) { res_ok = res_api; } _self.consoleLog("getApiOk : res_ok : ", res_ok); callback(res_ok); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi : api : ", api); _self.consoleLog("getApi : dataSend : ", dataSend); _self.consoleLog("getApi : res_api : ", res_api); _self.getApiOk(res_api, function(res_api_ok) { callback(res_api_ok); }); }); }, main: function() { var _self = this; } } return getFunction; }; $scope.getNavigationBar = function() { var getFunction = { chackCategory: function(categoryArray, callback) { var res_chack_category = (categoryArray != 0 && categoryArray != undefined) ? true : false; callback(res_chack_category); }, getReferralId: function(chackCategory, categoryArray, index, callback) { var res_referral_id = (chackCategory == true) ? categoryArray[index].referral_id : false; callback(res_referral_id); }, getData: function(api, referralId, callback) { if (referralId != false) { $scope.dataSet[1].dataSend = { 'txt_referral_id': referralId } $scope.getFunction().dataSend(api, $scope.dataSet[1].dataSend, function(api, dataSend) { $scope.getFunction().getApi(api, dataSend, function(res_api) { callback(res_api); }); }); } else { callback([]); } }, main: function(api, productReferralDisplay, callback) { var _self = this; _self.chackCategory(productReferralDisplay.category, function(res_chack_category) { _self.getReferralId(res_chack_category, productReferralDisplay.category, 0, function(res_referral_id) { _self.getData(api, res_referral_id, function(res_api) { callback(res_api); }); }); }); } } return getFunction; }; $scope.getFunction().getRouteParamsProductId(function(res_product_id) { $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(true, false); $scope.dataSet[0].dataSend = { 'txt_product_id': res_product_id } $scope.getFunction().dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { $scope.getFunction().getApi(api, dataSend, function(res_api) { $scope.getFunction().consoleLog("getRouteParamsProductId : dataSend : getApi : ", res_api); $scope.dataSet[0].dataArray = res_api.data; $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(false, true); $scope.getTab().pullData(0, res_api.data.product_description, function(index, res_data, res_state) { $scope.dataTab.tabArray[index].compileDetail = res_data; $scope.dataTab.tabArray[index].state = res_state; }); $scope.getTab().pullDataArray(1, res_api.data.product_attribute, function(index, res_data_array, res_state) { $scope.dataTab.tabArray[index].compileArray = res_data_array; $scope.dataTab.tabArray[index].state = res_state; }); $scope.getTab().pullData(2, res_api.data.product_more_info, function(index, res_data, res_state) { $scope.dataTab.tabArray[index].compileDetail = res_data; $scope.dataTab.tabArray[index].state = res_state; }); $scope.dataSet[1].dataSendState = $scope.getFunction().stateData(true, false); $scope.getNavigationBar().main($scope.dataSet[1].api, res_api.data.product_referral_display, function(red_navigation_bar) { $scope.getFunction().consoleLog("getNavigationBar : red_navigation_bar : ", red_navigation_bar); $scope.dataSet[1].dataArray = red_navigation_bar.data; $scope.dataSet[1].dataSendState = $scope.getFunction().stateData(false, true); }); }); }); }); }; return promise; }); _ui_share_app.directive('productDetailPageQ', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageQ'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id:'@id', headerheight:'@headerheight', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { }; promise.controller = function ($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; angular.element($window).bind('scroll',function(){ var curPos = ($(document).scrollTop()); var rightPos = $('product-detail-page-q .block-background .block-left .bottom-info').height(); var properHeight = ($('.img_cover').height()); console.debug("Cur pos",curPos, properHeight); if(curPos+rightPos-50 > properHeight){ angular.element('.block-background .bottom-info').addClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if($(window).width() > 991){ angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* Get product id from url or from component */ $scope._getPostIdFromURL = function(){ var test = $scope.id; var a = $scope.id; if(typeof $routeParams.product_id !== 'undefined'){ test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if(typeof test === 'number' && test > 0){ return test; } else { var b = a.split("-"); return b[0]; } }; $scope.data = false; $scope.dataPreserve = false; /* Get data by product id */ GAEAPI.get('product/id',{'txt_product_id':$scope._getPostIdFromURL()} , $scope).then(function(e){ if(e.ok == 1){ $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); /*$scope.buildDataProductRelate($scope._getPostIdFromURL());*/ } }); $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id){ var j = {'relate_product_id_array':[product_id],'badge_id_array':[18]}; var d = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists',d , $scope).then(function(e){ if(e.ok == 1){ $scope.dataRelate = e.data.dataList; console.log("dataRelate",$scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData){ if(objectData.product_total_variant <= 0){ return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; /*$scope.makeVariantsClick();*/ $scope.makeVaraintsClick_Normal(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.onClickVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick){ function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for(var i = 0; i < dataVariants.length; i++){ var optionJson = angular.fromJson(dataVariants[i].option_id_json); if(compareArray(variantsPick,optionJson)){ $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; /* Select FIrst Varaint (SELECT) */ $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; /* Select FIrst Varaint (Normal click) */ $scope.makeVaraintsClick_Normal = function(){ $timeout(function(){ $('div.variantSelector').each(function(idx,obj){ $(this).find('span[data-index="'+idx+'"]').eq(0).click(); }); },2000); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function () { var elementName = '.img_mobile[data-key="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope._makeProductToCarouseltwo = function () { var elementName = '.img_desktop[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-key="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-key="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if($('.img_mobile[data-key="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } if($('.img_desktop[data-id="'+$scope._key()+'"]').not('.slick-initialized')){ $timeout(function(){ $scope._makeProductToCarouseltwo(); }, 500); } }); $scope.buildIframeMapByLoc = function(name, lat, lng) { var newName = name; var YOUR_API_KEY = 'AIzaSyDU_QXXovpoO2nlyXBWbrCZdFeaApx-luU'; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } if (name != '') { var srcByName = 'https://www.google.co.th/maps?q=' + DataName + '&output=embed&hl=th-TH'; return srcByName; } else { var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return srcByLoc; } /*return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName;*/ }; $scope.qty_original=1; $scope.qty_current=1; $scope.getShopName = function(){ return (typeof tttt !== 'undefined') ? tttt.shop_name : ''; }; }; return promise; }); _ui_share_app.directive('productDetailPageSk', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageSk'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', icon: '@icon', stylebutton: '@stylebutton' }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayTags = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.showTab = { activeTab: 'description', dataTab: [{ en: 'description', th: 'รายละเอียดสินค้า', data: '' }, { en: 'info', th: 'วิธีการชำระเงินและวิธีการจัดส่ง', data: '' }] }; $scope.attribute = { state: false, attributeOption: [], variants: 'description', variantsPick: [], dataVariants: [], variantsTotal: 0 }; $scope.buy = { state: false, attribute: false }; $scope.processBuy = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, onClickFalse: function() { if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } } } return functionIn; }; $scope.attributeOption = function() { var functionIn = { consoleLog: function(name, data) { console.log("productDetailPageSk : ", name, data); }, checkVariantsPick: function(variantsPick) { if (variantsPick.length != 0) { var state = 0; for (var i = 0; i < variantsPick.length; i++) { if (variantsPick[i] == "") { state = state + 1; } } if (state == 0) { return true } else { return false } } else { return false } }, compareArray: function(attributeOption, optionJson) { if (!optionJson) return false; if (attributeOption.length != optionJson.length) return false; for (var i = 0, l = attributeOption.length; i < l; i++) { if (attributeOption[i] instanceof Array && optionJson[i] instanceof Array) { if (!compareArray(attributeOption[i], optionJson[i])) return false; } else if (attributeOption[i] != optionJson[i]) { return false; } } return true; }, checkAttributeOption: function(attributeOption, attributeOptionLength, callback) { var _self = this; var attribute = (attributeOption.length == attributeOptionLength) ? true : false; for (var i = 0; i < attributeOption.length; i++) { _self.consoleLog("checkAttributeOption : attributeOption[i] : ", attributeOption[i]); if (attributeOption[i] == undefined) { attribute = false; } } callback(attribute); }, findVariantsData: function(attributeOption, dataVariants, attributeOptionLength, callback) { var _self = this; _self.consoleLog("findVariantsData : attributeOption : ", attributeOption); _self.consoleLog("findVariantsData : dataVariants : ", dataVariants); _self.consoleLog("findVariantsData : attributeOptionLength : ", attributeOptionLength); _self.checkAttributeOption(attributeOption, attributeOptionLength, function(res_attribute_option) { _self.consoleLog("checkAttributeOption : callback : res_attribute_option ", res_attribute_option); var variantsOut = []; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (_self.compareArray(attributeOption, optionJson)) { _self.consoleLog("findVariantsData : dataVariants[i] : ", dataVariants[i]); variantsOut = dataVariants[i]; break; } } callback(variantsOut, res_attribute_option); }); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var _self = this; var state = true; _self.consoleLog("checkTotalStock : index : ", stateIn); _self.consoleLog("checkTotalStock : quantity_max : ", quantity_max); if (stateIn == false && quantity_max > 0) { state = false; } callback(state); }, onClickOption: function($index, option_id) { var _self = this; _self.consoleLog("onClickOption : index : ", $index); _self.consoleLog("onClickOption : option_id : ", option_id); $scope.attribute.variantsPick[$index] = option_id; _self.consoleLog("onClickOption : $scope.attribute.variantsPick[$index] : ", $scope.attribute.variantsPick[$index]); if ($scope.attribute.attributeOption.length >= $scope.attribute.variantsPick.length) { if (_self.checkVariantsPick($scope.attribute.variantsPick)) { _self.consoleLog("onClickOption : if : $scope.attribute.attributeOption.length : ", $scope.attribute.attributeOption.length); _self.consoleLog("onClickOption : if : $scope.attribute.variantsPick.length : ", $scope.attribute.variantsPick.length); _self.findVariantsData($scope.attribute.variantsPick, $scope.attribute.dataVariants, $scope.attribute.attributeOption.length, function(variantsOut, res_attribute_option) { _self.consoleLog("onClickOption : if : findVariantsData : variantsOut : ", variantsOut); _self.consoleLog("onClickOption : if : findVariantsData : res_attribute_option : ", res_attribute_option); if (variantsOut.length != 0 && res_attribute_option) { $scope.dataArray.product_id = variantsOut.product_id; $scope.dataArray.product_sku = variantsOut.sku; $scope.dataProductBuy.price = variantsOut.price; $scope.dataArray.product_compare_price = variantsOut.compare_price; $scope.dataProductBuy.quantity_max = variantsOut.total_stock; if (variantsOut.variant_image != 0) { if ($scope.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataArray.product_image.length; i++) { $scope.dataArray.product_image[i].image_id if ($scope.dataArray.product_image[i].image_id == variantsOut.variant_image[0].image_id) { $scope.slickImageGoto(i); } } } } _self.checkOption($scope.attribute.variantsTotal, function(state) { _self.checkTotalStock(state, variantsOut.total_stock, function(state) { $scope.buy.state = state; if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } }); }); } else if (variantsOut.length == 0 && res_attribute_option) { $scope.dataArray.product_id = 0; $scope.dataArray.product_sku = ''; $scope.dataProductBuy.price = 0; $scope.dataArray.product_compare_price = 0; $scope.dataProductBuy.quantity_max = 1; $scope.buy.state = true; $scope.buy.attribute = true; } $scope.quantity().input(); }); } } } } return functionIn; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity_max; } _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } } } return quantity; }; $scope.carouselId = ''; $scope.slickCarouselId = function() { if ($scope.carouselId == '') { $scope.carouselId = Math.floor((Math.random() * 9999) + 1000); return $scope.carouselId; } else { return $scope.carouselId; } }; $scope.slickImageGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope.carouselId + '"]').slick('slickGoTo', idx); }, 100); }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 100); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log('productDetailPageMaeju : ', name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getQuantityBreak: function(api, callback) { var _self = this; _self.getProductId(function(product_id) { var customerId = 0; if (UiCustomerBox.delegate.get.isLogin()) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); } var dataSendQuantityBreak = { 'txt_product_id': product_id, 'txt_customer_id': customerId }; var quantity_break = []; _self.getDataArray(api, dataSendQuantityBreak, function(output) { if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); }); }, quantity: function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.dataArray, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } }, showTab: function(input, callback) { var description = input.product_description; var info = input.product_more_info; callback(description, info); }, productTab: function(product_tags, callback) { var _self = this; _self.consoleLog("productTab : product_tags : ", product_tags); var productTab = []; if (product_tags != undefined) { if (product_tags != "") { productTab = product_tags.split(","); callback(productTab); } else { callback(productTab); } } else { callback(productTab); } }, getAttribute: function(input, callback) { var _self = this; var attribute = []; var variants = []; var variants_total = 0; _self.consoleLog("getAttribute : input : ", input); if (input.product_attribute.option_data !== 'undefined' && input.product_total_variant > 0) { _self.consoleLog("getAttribute : input.product_attribute.option_data : ", input.product_attribute.option_data); _self.consoleLog("getAttribute : input.product_total_variant : ", input.product_total_variant); if (input.product_attribute.option_data.pclass_array !== 'undefined' && input.product_attribute.option_data.pclass_array.length) { _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array : ", input.product_attribute.option_data.pclass_array); _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array.length : ", input.product_attribute.option_data.pclass_array.length); attribute = input.product_attribute.option_data.pclass_array; variants = input.product_attribute.option_data.variant_array; variants_total = input.product_total_variant; } } callback(variants_total, attribute, variants); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = true; if (stateIn == true && quantity_max > 0) { state = false; } callback(state); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, main: function() { var _self = this; $scope.slickCarouselId(); $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { if (output.data.length != 0) { _self.consoleLog(" : output : ", output.data); _self.quantity(output.data.product_total_stock, function(total_stock) { _self.consoleLog("quantity : total_stock : ", total_stock); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataArray = output.data; _self.productTab(output.data.product_tags, function(productTab) { $scope.dataArrayTags = productTab; _self.showTab(output.data, function(description, info) { $scope.showTab.dataTab[0].data = description; $scope.showTab.dataTab[1].data = info; }); _self.getAttribute(output.data, function(variants_total, attribute, variants) { _self.consoleLog("getAttribute : variants_total : ", variants_total); _self.consoleLog("getAttribute : attribute : ", attribute); _self.consoleLog("getAttribute : variants : ", variants); _self.checkOption(variants_total, function(state) { _self.checkTotalStock(state, total_stock, function(state) { $scope.buy.state = state; $scope.attribute.attributeOption = attribute; $scope.attribute.dataVariants = variants; $scope.attribute.variantsTotal = variants_total; if (variants_total > 0) { _self.checkPriceMin(variants, function(res_price, res_compare_price) { $scope.dataProductBuy.price = res_price; $scope.dataProductBuy.sumprice = res_price; $scope.dataArray.product_compare_price = res_compare_price; }); } else { $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; } }); }); }); _self.getQuantityBreak('product/quantity_break', function(quantity_break) { _self.consoleLog("getQuantityBreak : output : ", quantity_break); $scope.dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.dataProductBuy.result_price = quantity_break[0].unit_price; } }); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; $scope.dataArrayState = _self.stateData(false, true); }); }); }); } else { window.history.back(); } }); } } return data; }; $scope.getDataArray().main(); $scope.tab_id = 0; $scope.tabId = function(id) { $scope.tab_id = id; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.categoriesData = $scope.routeParams().referral_id || ''; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.checkPrice = function(price) { var check_price = 0; var _price = (price != undefined && price != "" && price != null) ? price.toString() : "0"; if (_price.includes(".")) { check_price = 2; } return check_price; }; $scope.dataShopCurrent = []; $scope.dataShopPointConfig = []; $scope.getShopCurrent = function() { var dataSend = {}; GAEAPI.get('shop/current', dataSend).then(function(output) { console.log("getShopCurrent : output : ", output); if (output.ok == 1) { $scope.dataShopCurrent = output.data; console.log("getShopCurrent : dataShopCurrent : ", $scope.dataShopCurrent); $scope.dataShopPointConfig = output.data.shop_point_config; console.log("getShopCurrent : dataShopPointConfig : ", $scope.dataShopPointConfig); } }); }; $scope.getShopCurrent(); $scope.getShopPointConfigReward = function(product_price, quantity) { var sup_price = 0; var er_rate = 0; var er_earn = 0; var mathFloor = 0; var point = 0; // console.log("getShopPointConfigReward : shop_point_config.er_rate : ",$scope.dataShopPointConfig.er_rate); if ($scope.dataShopPointConfig.length != 0) { sup_price = product_price * quantity; er_rate = parseInt($scope.dataShopPointConfig.er_rate); er_earn = parseInt($scope.dataShopPointConfig.er_earn); mathFloor = Math.floor(sup_price / er_rate); point = mathFloor * er_earn; return point; } else { return point; } } $scope.getShopPointConfigRewardState = function(product_price, quantity) { var state = 'RewardShop'; var sup_price = product_price * quantity; if ($scope.dataShopPointConfig.length != 0) { if (parseInt($scope.dataShopPointConfig.er_rate) != 0 && parseInt($scope.dataShopPointConfig.er_earn) != 0) { if (parseInt($scope.dataShopPointConfig.er_rate) <= sup_price) { state = 'RewardShop'; return state; } else { state = 'High'; return state; } } else { return 'RewardProduct'; return state; } } else { return 'RewardProduct'; } }; }; return promise; });_ui_share_app.directive('productDetailPageSupercheap', function($rootScope, $routeParams, sliderProvider, $location) { var templateName = 'productDetailPageSupercheap'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', navigationhover: '@navigationhover', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._component = "productDetailPageSupercheap"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._cart = ($scope.cart != undefined && $scope.cart != "") ? $scope.cart : "trumpComponentCarts"; $scope._buycol = ($scope.buycol != undefined && $scope.buycol != "") ? parseInt($scope.buycol) : 15; $scope._maxstock = ($scope.maxstock != undefined && $scope.maxstock != "") ? parseInt($scope.maxstock) : 20; $scope._btnstyle = ($scope.btnstyle != undefined && $scope.btnstyle != "") ? $scope.btnstyle : "filled_button_large"; $scope._buylogin = ($scope.buylogin == "true" || $scope.buylogin == "t") ? true : false; $scope._checkstaff = ($scope.checkstaff == "true" || $scope.checkstaff == "t") ? true : false; $scope._buyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope.buyicon : "icnt_outline_cart01_dark.png"; $scope._buytext = ($scope.buytext != undefined && $scope.buytext != "") ? $scope.buytext : "เพิ่มในรถเข็น"; $scope._videotext = ($scope.videotext != undefined && $scope.videotext != "") ? $scope.videotext : "Video"; $scope._icebuyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope._icnPath + $scope.buyicon : $scope._icnPath + "icnt_outline_cart01_dark.png"; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; $scope._navigationhover = ($scope.navigationhover != undefined && $scope.navigationhover != "") ? $scope.navigationhover : "primary"; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getNamePage: function(arr) { var str = []; for (var i = 0; i < arr.length; i++) { if (i != 0) { str.push(arr[i]); } } return str.join(" "); }, getProductId: function(params, callback) { var _self = this; var product_id = (params.product_id != undefined) ? params.product_id.split("-", 1).join("") : false; _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getReferralId: function(productReferralDisplay, callback) { var _self = this; var referral_id = 0; if (productReferralDisplay.length != 0) { if (productReferralDisplay.category != undefined) { if (productReferralDisplay.category.length != 0) { referral_id = productReferralDisplay.category[0].referral_id } } } callback(referral_id); }, getFreeGiftPromotionId: function(product_promotion, callback) { var _self = this; var promotion_id = '0'; _self.consoleLog("product_promotion", product_promotion); angular.forEach(product_promotion, function(item, index) { _self.consoleLog("product_promotion : item", item.promotion_type_id); if (promotion_id == '0' && (item.promotion_type_number == '1' || item.promotion_type_number == '2' || item.promotion_type_number == '3')) { promotion_id = item.promotion_id; } }); callback(promotion_id); }, getStaffId: function(staffId, callback) { var _self = this; var res_staff = { staff_id: (staffId != 0 && staffId != '' && staffId != undefined) ? staffId : '0', status: (staffId != 0 && staffId != '' && staffId != undefined) ? true : false } callback(res_staff); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carouselA: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ fade: true, dots: false, arrows: false, infinite: true, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselB: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: true, arrows: true, infinite: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselD: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: false, arrows: true, infinite: true, autoplay: true, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselBar: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: false, arrows: false, infinite: false, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 6, slidesToScroll: 6, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 5, slidesToScroll: 5, } }, { breakpoint: 991, settings: { slidesToShow: 4, slidesToScroll: 4, } }, { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 3, } }] }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, slickCarousel: function(carousel, index) { var _self = this; $scope.setCarousel.index = index; setTimeout(function() { $('[data-key="' + carousel + '"]').slick('slickGoTo', index); }, 100); }, prevIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != 0) ? image_index - 1 : image - 1; _self.consoleLog("prevIndex index", $scope.setCarousel.index); }, nextIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != (image - 1)) ? image_index + 1 : 0; _self.consoleLog("nextIndex index", $scope.setCarousel.index); } } return getFunction; }; $scope.getAttribute = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, productAttribute: function(productAttribute, callback) { var _self = this; var attribute = { option_name: "", option_attribute: [] }; if (productAttribute.option_data != undefined) { if (productAttribute.option_data.variant_array != undefined && productAttribute.option_data.variant_array.length != 0) { for (var a = 0; a < productAttribute.option_data.pclass_array.length; a++) { attribute.option_name = attribute.option_name.concat(productAttribute.option_data.pclass_array[a].pclass_name, " "); } for (var b = 0; b < productAttribute.option_data.variant_array.length; b++) { var product_attribute = { product_id: productAttribute.option_data.variant_array[b].product_id, product_sku: productAttribute.option_data.variant_array[b].sku, product_title: "", product_price: parseFloat(productAttribute.option_data.variant_array[b].price), product_compare_price: parseFloat(productAttribute.option_data.variant_array[b].compare_price), product_total_stock: parseFloat(productAttribute.option_data.variant_array[b].total_stock), product_image: productAttribute.option_data.variant_array[b].variant_image } for (var c = 0; c < productAttribute.option_data.variant_array[b].option_name_array.length; c++) { product_attribute.product_title = product_attribute.product_title.concat(productAttribute.option_data.variant_array[b].option_name_array[c], " "); } attribute.option_attribute.push(product_attribute); } } } _self.consoleLog("productAttribute attribute ", attribute); callback(attribute); }, checkDiscountPrice: function(productDiscount, resPrice, resComparePrice, callback) { var _self = this; var price = 0; var compare_price = 0; if (productDiscount.length == 0) { price = parseFloat(resPrice); compare_price = parseFloat(resComparePrice); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(resPrice) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(resPrice); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(resPrice) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(resPrice); } } callback(price, compare_price); }, checkMinPrice: function(option, callback) { var _self = this; var price_min = parseFloat(option.option_attribute[0].product_price); var compare_price_min = parseFloat(option.option_attribute[0].product_compare_price); var total_stock = parseFloat(option.option_attribute[0].product_total_stock); for (var a = 0; a < option.option_attribute.length; a++) { if (price_min >= parseFloat(option.option_attribute[a].product_price)) { price_min = parseFloat(option.option_attribute[a].product_price); compare_price_min = parseFloat(option.option_attribute[a].product_compare_price); total_stock = parseFloat(option.option_attribute[a].product_total_stock); } } _self.consoleLog("checkPriceMin price_min ", price_min); _self.consoleLog("checkPriceMin compare_price_min ", compare_price_min); _self.consoleLog("checkPriceMin total_stock ", total_stock); callback(price_min, compare_price_min, total_stock); }, getTotalStock: function(totalStock, mixStock, callback) { var _self = this; var total_stock = (totalStock > 0) ? ((totalStock <= mixStock) ? totalStock : mixStock) : ((totalStock == -1) ? mixStock : totalStock); callback(total_stock); }, checkMinPrices: function(api, attribute, callback) { var _self = this; var dataPrice = { product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 } } if (attribute.option_attribute.length == 0) { _self.checkDiscountPrice(api.data.product_discount, api.data.product_price, api.data.product_compare_price, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(api.data.product_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, false); }); }); }); }); }); } else { _self.checkMinPrice(attribute, function(res_price_min, res_compare_price_min, res_total_stock) { _self.checkDiscountPrice(api.data.product_discount, res_price_min, res_compare_price_min, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(res_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, true); }); }); }); }); }); }); } }, priceIncludes: function(price, includes, callback) { var _self = this; var priceToString = (price == null) ? 0 : price; _self.consoleLog('priceIncludes priceToString : ', priceToString); callback(priceToString.toString().includes(includes)); }, checkPrice: function(price, callback) { var _self = this; _self.priceIncludes(price, '.', function(res) { _self.consoleLog("checkPrice res ", res); callback((!res) ? 0 : 2); }); }, onSelectOption: function(productId) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = productId; _self.consoleLog("onSelectOption productId ", productId); $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); for (var a = 0; a < $scope.data.attribute.dataArray.option_attribute.length; a++) { _self.consoleLog("onSelectOption option_attribute ", $scope.data.attribute.dataArray.option_attribute[a]); if ($scope.data.attribute.dataArray.option_attribute[a].product_id == productId) { if ($scope.data.attribute.dataArray.option_attribute[a].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var b = 0; b < $scope.dataApi.product.dataArray.product_image.length; b++) { if ($scope.dataApi.product.dataArray.product_image[b].image_id == $scope.data.attribute.dataArray.option_attribute[a].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, b); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[a].product_price, $scope.data.attribute.dataArray.option_attribute[a].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[a].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); break; } } }, onClickOption: function(index) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.data.attribute.productId = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); if ($scope.data.attribute.dataArray.option_attribute[index].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataApi.product.dataArray.product_image.length; i++) { if ($scope.dataApi.product.dataArray.product_image[i].image_id == $scope.data.attribute.dataArray.option_attribute[index].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, i); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[index].product_price, $scope.data.attribute.dataArray.option_attribute[index].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[index].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); } } return getFunction; }; $scope.getAttributeCustom = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, createArray: function(productCustomTemplates, callback) { var _self = this; var custom_attributes = []; if (productCustomTemplates.templates.length != 0) { angular.forEach(productCustomTemplates.templates, function(item, index) { if (item.option_sets.length != 0) { _self.getAttributes(item.option_sets, function(res_attributes) { custom_attributes = custom_attributes.concat(res_attributes); }); } }); /* if (productCustomTemplates.templates[0].option_sets.length != 0) { _self.getAttributes(productCustomTemplates.templates[0].option_sets, function(res_attributes) { custom_attributes = res_attributes; }); } */ } _self.consoleLog("createArray : productCustomTemplates", productCustomTemplates); _self.consoleLog("createArray : custom_attributes", custom_attributes); callback(custom_attributes, true); }, formatAttribute: function(index, optionSubsetIndex, setType, optionSetArray, callback) { var _self = this; var set_id = (setType == 'attribute') ? optionSetArray.set_id : optionSetArray.subset_id; var attribute = { attribute_index: index, attribute_option_subset_index: optionSubsetIndex, active_option_id: (optionSetArray.option_data.select_id != 0) ? optionSetArray.option_data.select_id : "-1", active_option_index: -1, active_option_index_str: "-1", active_textarea: "", active_array: [], set_id: set_id, name: optionSetArray.name, set_type: optionSetArray.ss_type, option: [] } callback(attribute); }, getOption: function(index, optionDataArray, callback) { var _self = this; var options = { index: index, ss_data_id: optionDataArray.ss_data_id, name: optionDataArray.name, image: optionDataArray.image, price: optionDataArray.price, compare_price: 0, total_stock: 0 } callback(options); }, getActive: function(index, activeOptionId, activeOptionIdIn, optionDataArray, callback) { var _self = this; var actives_index = (optionDataArray.ss_data_id == activeOptionId) ? index : activeOptionIdIn; var actives = (optionDataArray.ss_data_id != activeOptionId) ? "0" : "1"; callback(actives_index, actives); }, getAttributes: function(optionSetArray, callback) { var _self = this; var attributes = []; for (var index = 0; index < optionSetArray.length; index++) { _self.formatAttribute(index, 0, 'attribute', optionSetArray[index], function(res_attribute) { if (optionSetArray[index].option_subsets.length != 0) { for (var option_subset_index = 0; option_subset_index < optionSetArray[index].option_subsets.length; option_subset_index++) { _self.formatAttribute(index, option_subset_index, res_attribute.set_type, optionSetArray[index].option_subsets[option_subset_index], function(res_attribute_sub) { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_subsets[option_subset_index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute_sub.active_option_id, active_option_id, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute_sub.option = options; res_attribute_sub.active_option_index = active_option_id; res_attribute_sub.active_option_index_str = String(active_option_id); res_attribute_sub.active_array = active_option_array; attributes.push(res_attribute_sub); }); } } else { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute.active_option_id, active_option_id, optionSetArray[index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute.option = options; res_attribute.active_option_index = active_option_id; res_attribute.active_option_index_str = String(active_option_id); res_attribute.active_array = active_option_array; attributes.push(res_attribute); } }); } callback(attributes) }, getformatQuantity: function(index, attributeCustom, callback) { var _self = this; var quantity = { name: String(index + 1), dataArray: attributeCustom } callback(quantity); }, onClickRadio: function(index, index_option) { var _self = this; _self.consoleLog("onClickRadio : index", index); _self.consoleLog("onClickRadio : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickRadio : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickDropdown: function(index, index_option) { var _self = this; _self.consoleLog("onClickDropdown : index", index); _self.consoleLog("onClickDropdown : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickDropdown : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickCheckbox: function(index, index_option) { var _self = this; _self.consoleLog("onClickCheckbox : index", index); _self.consoleLog("onClickCheckbox : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i == parseInt(index_option)) ? (($scope.data.attribute_custom.dataArray[index].active_array[i] != "0") ? "0" : "1") : $scope.data.attribute_custom.dataArray[index].active_array[i]; } _self.consoleLog("onClickCheckbox : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); } } return getFunction; }; $scope.getReward = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, momentUnix: function(callback) { var _self = this; var now = moment().unix(); callback(now); }, getCalculator: function(sumProductPrice, reward, callback) { var _self = this; _self.consoleLog("getCalculator : sumProductPrice", sumProductPrice); _self.consoleLog("getCalculator : reward", reward); var point_reward = 0; if (reward.type_id == "100") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } else if (reward.type_id == "101") { point_reward = reward.reward_amount; } else if (reward.type_id == "102") { point_reward = (reward.reward_percent * sumProductPrice.price) / 100; } else if (reward.type_id == "103") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } _self.consoleLog("getCalculator : point_reward", point_reward); callback(point_reward); }, getProductReward: function(now, productReward, callback) { var _self = this; var reward = { reward_length: (productReward.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(productReward.reward_lifetime.lifetime_start_time); reward.lifetime_end_time = parseInt(productReward.reward_lifetime.lifetime_end_time); reward.type_id = productReward.reward_type_id; reward.amount = parseInt(productReward.reward_amount); reward.percent = parseInt(productReward.reward_percent); reward.every_price = parseInt(productReward.reward_every_price); } _self.consoleLog("getProductReward : reward", reward); callback(reward); }, getPointConfig: function(now, shopPointConfig, callback) { var _self = this; var reward = { reward_length: (shopPointConfig.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(shopPointConfig.er_from); reward.lifetime_end_time = parseInt(shopPointConfig.er_to); reward.type_id = "100"; reward.amount = parseInt(shopPointConfig.er_earn); reward.every_price = parseInt(shopPointConfig.er_rate); } _self.consoleLog("getPointConfig : reward", reward); callback(reward); }, checkPointReward: function(reward, callback) { var _self = this; var state = false; if (reward.reward_length) { var start = reward.lifetime_start_time < reward.lifetime_time && reward.lifetime_start_time != 0; var end = (reward.lifetime_end_time != -1) ? reward.lifetime_time <= reward.lifetime_end_time && reward.lifetime_end_time != 0 : true; if (start && end) { if (reward.type_id == "100") { var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } else if (reward.type_id == "101") { var amount = reward.amount != 0; if (amount) { state = true; } } else if (reward.type_id == "102") { var percent = reward.percent != 0; if (percent) { state = true; } } else if (reward.type_id == "103") { var percent = reward.percent != 0; var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } } } callback(state); }, checkReward: function(rewardProduct, rewardPointConfig, callback) { var _self = this; _self.consoleLog("checkReward : rewardProduct", rewardProduct); _self.consoleLog("checkReward : rewardPointConfig", rewardPointConfig); var reward = { type_id: "0", amount: 0, percent: 0, every_price: 0 }; _self.checkPointReward(rewardProduct, function(res_state_product) { _self.checkPointReward(rewardPointConfig, function(res_state_point_config) { if (res_state_point_config) { reward.type_id = rewardPointConfig.type_id; reward.type_id = rewardPointConfig.type_id; reward.amount = rewardPointConfig.amount; reward.percent = rewardPointConfig.percent; reward.every_price = rewardPointConfig.every_price; } else if (res_state_product) { reward.type_id = rewardProduct.type_id; reward.amount = rewardProduct.amount; reward.percent = rewardProduct.percent; reward.every_price = rewardProduct.every_price; } _self.consoleLog("checkReward : reward", reward); callback(reward); }); }); }, checkRewardType: function(productReward, shopPointConfig, callback) { var _self = this; _self.momentUnix(function(now) { _self.getProductReward(now, productReward, function(res_reward_product) { _self.getPointConfig(now, shopPointConfig, function(res_reward_point_config) { _self.checkReward(res_reward_product, res_reward_point_config, function(res_reward) { callback(res_reward); }); }); }); }); }, createReward: function(productReward, shopPointConfig, callback) { var _self = this; _self.consoleLog("createReward : productReward", productReward); _self.consoleLog("createReward : shopPointConfig", shopPointConfig); _self.checkRewardType(productReward, shopPointConfig, function(res_reward) { _self.consoleLog("createReward : res_reward", res_reward); callback(res_reward); }); } } return getFunction; }; $scope.getQuantity = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, upDateReward: function() { var _self = this; }, upDateReward: function() { var _self = this; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); }, upDatePrice: function() { var _self = this; var product_price = $scope.data.product_price.price * $scope.data.quantity.quantity_input; var product_compare_price = $scope.data.product_compare_price.price * $scope.data.quantity.quantity_input; $scope.getAttribute().checkPrice(product_price, function(res_price_ecimals) { $scope.data.sum_product_price.price = product_price; $scope.data.sum_product_price.price_ecimals = res_price_ecimals; $scope.getAttribute().checkPrice(product_compare_price, function(res_compare_price_ecimals) { $scope.data.sum_product_compare_price.price = product_compare_price; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((product_compare_price - product_price) > 0) ? product_compare_price - product_price : 0; $scope.getAttribute().checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.upDateReward(); }); }); }); }, input: function(quantityInput) { var _self = this; quantityInput = (quantityInput == null) ? 1 : parseInt(quantityInput); _self.consoleLog("input : quantityInput", quantityInput); if (quantityInput != null) { if (quantityInput >= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_max; } if (quantityInput <= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } } else { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } _self.upDatePrice(); }, minus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input - 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_min", $scope.data.quantity.quantity_min); if (quantity >= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); }, plus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input + 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_max", $scope.data.quantity.quantity_max); if (quantity <= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); } } return getFunction; }; $scope.getBuy = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getProductId: function(params, callback) { var _self = this; var product_id = params.product_id.split("-", 1).join(""); _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, postApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.post(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, UiCartProductAdd: function(productId, quantityInput, promotionId, customOptions, callback) { UiCart.delegate.product.add(productId, quantityInput, promotionId, function(res_data) { callback(res_data); }); }, isLogin: function(callback) { var buy_login = $scope._buylogin; var is_login = UiCustomerBox.delegate.get.isLogin(); var is_state = (buy_login) ? (!is_login) ? true : false : false; callback(is_state); }, formLogin: function(is_state, callback) { if (is_state) { $inloginPopup.open(); } callback(is_state); }, getProductStaffId(staff_id_check, callback) { var res_staff_id_check = staff_id_check; var res_staff_id = $scope.dataApi.product.dataArray.product_staff_id; var res_is_state = (res_staff_id != 0 && res_staff_id != '0' && res_staff_id != undefined) ? true : false; callback(res_staff_id_check, res_staff_id, res_is_state); }, isStaffId: function(staff_id_check, callback) { /* todo */ var _self = this; _self.getProductStaffId(staff_id_check, function(res_staff_id_check, res_staff_id, res_is_state) { callback(res_staff_id_check, res_staff_id, res_is_state); }); }, checkCartDuplicateStaff: function(res_staff_id_check, txt_staff_id, res_is_state, callback) { var _self = this var res_is_state = true; if (res_staff_id_check) { var dataSend = { 'txt_staff_id': txt_staff_id, }; _self.dataSend("cart/duplicate_staff", dataSend, function(res_api, res_dataSend) { _self.postApi(res_api, res_dataSend, function(res_ok, res_api, state) { res_is_state = res_api.data.duplicate; callback(res_is_state); }); }); } else { callback(res_is_state); } }, showAlert: function(res_staff_id_check, res_staff_id, res_is_state, res_api, callback) { var res_state = (res_staff_id_check) ? ((res_api) ? ((res_is_state) ? false : true) : true) : false; if (res_state) { if (!res_api) { if (res_staff_id != '0' && res_staff_id != 0) { $scope.controlAlert().alert('002'); } else { $scope.controlAlert().alert('003'); } } else { if (!res_is_state) { $scope.controlAlert().alert('003'); } } } callback(res_state); }, checkStaff: function(callback) { var _self = this var staff_id_check = $scope._checkstaff; var res_check = false; _self.isStaffId(staff_id_check, function(res_staff_id_check, res_staff_id, res_is_state) { _self.checkCartDuplicateStaff(res_staff_id_check, res_staff_id, res_is_state, function(res_api) { _self.showAlert(res_staff_id_check, res_staff_id, res_is_state, res_api, function(res_state) { res_check = res_state; callback(res_check); }); }); }); }, isProgress: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isProgress(productId)) ? true : false; _self.consoleLog("isProgress : productId", productId); _self.consoleLog("isProgress : state", state); callback(state); }, isSelected: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isSelected(productId)) ? true : false; _self.consoleLog("isSelected : productId", productId); _self.consoleLog("isSelected : state", state); callback(state); }, isSelectedReturn: function(productId) { var _self = this; var ui_cart_state = (UiCart.delegate.product.isSelected(productId)) ? true : false; if (!$scope.setBuy.state_active) { $scope.setBuy.state_active = true; var state_process = $scope.setBuy.state_process; var state_step = $scope.setBuy.state_step; if (ui_cart_state && !state_process && state_step != 4) /* cart */ { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else if (!ui_cart_state && !state_process && state_step != 0) /* unset */ { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } else { $scope.setBuy.state_active = false; } } return ui_cart_state; }, updateState: function(productId) { _self = this; _self.isSelected(productId, function(res_state) { if (res_state) { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } return res_state; }); }, uiCart: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; _self.UiCartProductAdd(productId, quantityInput, promotionId, customOptions, function(res_data) { if (res_data) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; if ($scope._cart == "trumpComponentCarts") { _self.trumpComponentCarts(); } }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }, postApiA: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; var custom_options = {}; var dataSend = { 'txt_product_id': productId, 'txt_amount': quantityInput, 'txt_is_clear_cart_before': "0", 'txt_custom_options_json': JSON.stringify(custom_options) }; _self.dataSend("cart/product_add", dataSend, function(res_api, res_dataSend) { _self.postApi(res_api, res_dataSend, function(res_ok, res_api, state) { if (res_ok) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }); }, onProcess: function(data, productId, quantityInput, promotionId, customOptions) { var _self = this; _self.isLogin(function(res_is_login) { _self.formLogin(res_is_login, function(res_form) { _self.checkStaff(function(res_is_state) { if (!$scope.setBuy.state_process && !res_form && !res_is_state) { $scope.setBuy.state_process = true; _self.isSelected(productId, function(res_state) { if (!res_state) { _self.onLoad($scope.setBuy.state_step, function(res_step) { if (data.sum_product_price.price != 0 && data.quantity.quantity_max != 0 && (data.attribute.state == (data.attribute.productId != ''))) { /* UiCart */ _self.uiCart(productId, quantityInput, promotionId, customOptions, res_step); /* api post offline */ /*_self.postApiA(productId, quantityInput, promotionId, customOptions, res_step); */ } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); } else { $scope.setBuy.state_process = false; if ($scope._cart == "trumpComponentCarts") { _self.trumpComponentCarts(); } else if ($scope._cart == "viewcart") { _self.viewCart($scope._cart); } } }); } }); }); }); }, onTimeout: function(time, callback) { var _self = this; var load = $timeout(function() { $timeout.cancel(load); callback(true) }, time); }, onUnset: function(step, callback) { var _self = this; step = (step == 0) ? 0 : 0; $scope.setBuy.state_step = step; callback(step); }, onLoad: function(step, callback) { var _self = this; step = (step == 0 || step == 1) ? 1 : 0; $scope.setBuy.state_step = step; callback(step); }, onPass: function(step, callback) { var _self = this; step = (step == 1 || step == 2) ? 2 : 0; $scope.setBuy.state_step = step; callback(step); }, onError: function(step, callback) { var _self = this; step = (step == 1 || step == 3) ? 3 : 0; $scope.setBuy.state_step = step; callback(step); }, onCart: function(step, callback) { var _self = this; step = (step == 2 || step == 4) ? 4 : 0; $scope.setBuy.state_step = step; callback(step); }, trumpComponentCarts: function() { var controlCart = share.getTrumpComponentCarts(); var component_carts = $('.cover-cards').hasClass('active'); if (!component_carts) { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.cart(); } } else { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.load(); } } }, viewCart: function(viewcart) { var _self = this; _self.pageUrl(viewcart); }, locationUrlReplace: function(page) { $location.url(page).replace(); }, pageUrl: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page); }, main: function(callback) { var _self = this; } } return getFunction; }; $scope.getDetail = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getDetail: function(api, callback) { var _self = this; var description = api.product_description; var info = api.product_more_info; var specificatio = []; if (api.product_attribute.specification_data != undefined) { specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? api.product_attribute.specification_data.pclass_array : []; } var state_specificatio = false; if (api.product_attribute.specification_data != undefined) { state_specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? true : false; } var state_info = (api.product_is_more_info == 1) ? true : false; _self.consoleLog("getDetail : description", description); _self.consoleLog("getDetail : info", info); _self.consoleLog("getDetail : state_info", state_info); _self.consoleLog("getDetail : specificatio", specificatio); _self.consoleLog("getDetail : state_specificatio", state_specificatio); callback(description, info, state_info, specificatio, state_specificatio); }, onClickDetail: function(index) { var _self = this; $scope.data.detail.active = index; _self.consoleLog("onClickDetail : data.detail.active", $scope.data.detail.active); } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageName: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page_name); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.countDown = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getLocation: function(callback) { var _self = this; var res_location = $location; _self.consoleLog("getLocation", "res_location", res_location); callback(res_location); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; _self.consoleLog("getRouteParams", "params", params); callback(params); }, getLocationUrlNameProductDetail: function(callback) { var _self = this; _self.getRouteParams(function(res_params) { _self.getLocation(function(res_location) { var url_page_name = "/product-detail/" + res_params.product_id; var res_url_name_product_detail = (res_location.url() == url_page_name) ? true : false; _self.consoleLog("getLocationUrlNameProductDeal", "res_url_name_product_detail", res_url_name_product_detail); callback(res_url_name_product_detail); }); }); }, getUnix: function(callback) { var _self = this; var now = moment().unix(); _self.consoleLog("getUnix", "now", now); callback(now); }, getCountDown: function(now, product_lifetime, callback) { var _self = this; var countdown_unix = parseInt(product_lifetime.lifetime_end_time) - now; var milliseconds = moment.duration(countdown_unix * 1000, "milliseconds"); var res_countdown = ((milliseconds.days() <= 9) ? '0' + milliseconds.days() : milliseconds.days()); res_countdown = res_countdown + ' : ' + ((milliseconds.hours() <= 9) ? '0' + milliseconds.hours() : milliseconds.hours()); res_countdown = res_countdown + ' : ' + ((milliseconds.minutes() <= 9) ? '0' + milliseconds.minutes() : milliseconds.minutes()); res_countdown = res_countdown + ' : ' + ((milliseconds.seconds() <= 9) ? '0' + milliseconds.seconds() : milliseconds.seconds()); _self.consoleLog("getCountDown", "res_countdown", res_countdown); callback(res_countdown, countdown_unix); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page); }, countDownByProduct: function(now, data_array, callback) { var _self = this; if (data_array.length != 0) { if (data_array.product_lifetime.length != 0) { _self.getCountDown(now, data_array.product_lifetime, function(res_count_down, res_countdown_unix) { data_array.product_lifetime.lifetime_countdown = (res_countdown_unix > 0) ? res_count_down : ""; if (data_array.product_lifetime.lifetime_countdown == "") { _self.getNameUrl(data_array.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", data_array.product_set_array[0].product_id, res_name); }); } }); } } _self.consoleLog("countDownByProduct", "data_array", data_array); callback(data_array); }, loop: function() { var _self = this; var load = $timeout(function() { $timeout.cancel(load); _self.getUnix(function(res_now) { _self.countDownByProduct(res_now, $scope.dataApi.product.dataArray, function(data_array) { $scope.dataApi.product.dataArray = data_array; _self.getLocationUrlNameProductDetail(function(res_url_name_product_detail) { if (res_url_name_product_detail) { _self.loop(); } }); }); }); }, 1000); } } return getFunction; }; $scope.control = function() { var getFunction = { popupVideo: function(state, video_link, video_embed_code) { var _self = this; if (video_embed_code != '') { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } else if (video_link != '') { window.open(video_link, '_blank'); } else { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } }, main: function() { var _self = this; } } return getFunction; }; $scope.data_control = { page_video: { popup: false, shop_video_embed_code: "" } } $scope.control_alert = { alert: { error_id: '', index: null, state: true, error: [{ id: '001', title: 'การสั่งซื้อ', messages: 'สามารถสั่งซื้อได้เพียงทีละออเดอร์เท่านั้น' }, { id: '002', title: 'การเพิ่มสินค้า', messages: 'ไม่สามารถเพิ่มสินค้าของร้านมากกว่า 1 ร้านค้าได้' }, { id: '003', title: 'การสั่งซื้อ', messages: 'ไม่สามารถเพิ่มสินค้า(ไม่มีร้านค้า)' }] } }; $scope.controlAlert = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getErrorMessages: function(error_id, callback) { var _self = this; var messages = { res_error_id: '', res_index: null } angular.forEach($scope.control_alert.alert.error, function(item, index) { if (item.id == error_id) { messages.res_error_id = item.id; messages.res_index = index; } }); callback(messages.res_error_id, messages.res_index); }, alert: function(error_id) { var _self = this; _self.getErrorMessages(error_id, function(res_error_id, res_index) { $scope.control_alert.alert.error_id = res_error_id; $scope.control_alert.alert.index = res_index; $scope.control_alert.alert.state = (!$scope.control.alert && res_error_id != '') ? true : false; }); }, main: function() { var _self = this; } } return getFunction; }; $scope.countDown().loop(); /* set carousel */ $scope.setCarousel = { carousel: 0, index: 0 }; $scope.getCarousel().getCarousel($scope.setCarousel.carousel, function(res_carousel_id) { $scope.setCarousel.carousel = res_carousel_id; }); /* set carousel */ /* get product api */ $scope.dataApi = { reward: { dataSend: {}, api: "shop/current", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, staff: { dataSend: { txt_staff_id: 0 }, api: "staff/id", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, product: { dataSend: { txt_product_id: 0 }, api: "product/id", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, relation: { dataSend: { txt_referral_id: 0 }, api: "referral/relation", ok: false, dataArray: [], dataArrayState: { load: false, done: false } } }; $scope.data = { attribute: { state: false, productId: "", dataArray: [] }, attribute_custom: { state: false, dataArray: [] }, reward: { quantity_name: 'reward', type_id: "0", reward_amount: 0, reward_percent: 0, reward_every_price: 0, point_reward: 0 }, quantity: { quantity_name: 'quantity', quantity_min: 1, quantity_max: 1, quantity_input: 1, quantity_select: [] }, product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, detail: { active: '0', dataArray: [{ index: '0', state: true, en: ($scope.description != undefined && $scope.description != "") ? $scope.description : 'Description', th: '', data: '', dataArray: [] }, { index: '1', state: true, en: ($scope.info != undefined && $scope.info != "") ? $scope.info : 'Info', th: '', data: '', dataArray: [] }, { index: '2', state: true, en: ($scope.specification != undefined && $scope.specification != "") ? $scope.specification : 'Specification', th: '', data: '', dataArray: [] }] } }; $scope.setBuy = { promotion_id: '0', state_active: false, state_process: false, state_step: 0, state_data_font_color: "", state_data_background_color: "", stepArray: [{ step: 0, name: "unset", icon: $scope._icebuyicon, state: "เพิ่มในรถเข็น", data_font_color: "", data_background_color: "" }, { step: 1, name: "load", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 2, name: "pass", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 3, name: "error", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 4, name: "cart", icon: "", state: "ดูรถเข็น", data_font_color: "", data_background_color: "primary_darkest" }] }; /* - get api product/id start - */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.product.dataArrayState = res_state; $scope.getData().getProductId(res_params, function(res_product_id) { $scope.dataApi.product.dataSend.txt_product_id = (res_product_id != false) ? res_product_id : 0; $scope.getData().dataSend($scope.dataApi.product.api, $scope.dataApi.product.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_product, res_state) { $scope.dataApi.product.ok = res_ok; $scope.dataApi.product.dataArray = get_res_api_product.data; $scope.getData().consoleLog("get_res_api_product", get_res_api_product); $scope.dataApi.product.dataArrayState = res_state; /* -- get api shop/current to reward -- */ if (res_ok) { /* -- get free gift promotion id -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.getData().getFreeGiftPromotionId(get_res_api_product.data.product_promotion, function(res_promotion_id) { $scope.setBuy.promotion_id = res_promotion_id; }); }); /* -- get free gift promotion id -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.reward.dataArrayState = res_state; $scope.getData().dataSend($scope.dataApi.reward.api, $scope.dataApi.reward.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_shop, res_state) { $scope.dataApi.reward.ok = res_ok; $scope.dataApi.reward.dataArray = get_res_api_shop.data; $scope.dataApi.reward.dataArrayState = res_state; $scope.getReward().createReward($scope.dataApi.product.dataArray.product_reward, get_res_api_shop.data.shop_point_config, function(res_reward) { $scope.data.reward.type_id = res_reward.type_id; $scope.data.reward.reward_amount = res_reward.amount; $scope.data.reward.reward_percent = res_reward.percent; $scope.data.reward.reward_every_price = res_reward.every_price; /* --- Wait product/id ,shop/current --- /* ---- get attribute ---- */ $scope.getAttribute().productAttribute(get_res_api_product.data.product_attribute, function(res_attribute) { $scope.data.attribute.dataArray = res_attribute; $scope.getAttribute().checkMinPrices(get_res_api_product, res_attribute, function(res_data_price, res_state) { $scope.data.attribute.state = res_state; $scope.data.product_price = res_data_price.product_price; $scope.data.product_compare_price = res_data_price.product_compare_price; $scope.data.sum_product_price = res_data_price.sum_product_price; $scope.data.sum_product_compare_price = res_data_price.sum_product_compare_price; $scope.data.sum_product_compare_minus_sum_product_price = res_data_price.sum_product_compare_minus_sum_product_price; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); /* ----- stock ----- */ $scope.data.quantity.quantity_max = res_data_price.product_price.total_stock; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_data_price.product_price.total_stock; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* ----- stock ----- */ }); }); /* ---- get attribute ---- */ /* ---- get attribute custom ---- */ $scope.getAttributeCustom().createArray(get_res_api_product.data.product_custom_templates, function(res_custom_attribute, res_state) { $scope.data.attribute_custom.state = res_state; $scope.data.attribute_custom.dataArray = res_custom_attribute; }); /* ---- get attribute custom ---- */ /* ---- get detail ---- */ $scope.getDetail().getDetail(get_res_api_product.data, function(res_description, res_info, res_state_info, res_specificatio, res_state_specificatio) { $scope.data.detail.dataArray[0].data = res_description; $scope.data.detail.dataArray[1].data = res_info; $scope.data.detail.dataArray[1].state = res_state_info; $scope.data.detail.dataArray[2].dataArray = res_specificatio; $scope.data.detail.dataArray[2].state = res_state_specificatio; }); /* ---- get detail ---- */ /* ---- update state ---- */ $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); /* ---- update state ---- */ /* --- Wait product/id ,shop/current --- */ }); }); }); }); /* -- get api shop/current to reward -- */ /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.relation.dataArrayState = res_state; $scope.getData().getReferralId(get_res_api_product.data.product_referral_display, function(res_referral_id) { $scope.dataApi.relation.dataSend.txt_referral_id = res_referral_id; $scope.getData().dataSend($scope.dataApi.relation.api, $scope.dataApi.relation.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_referral, res_state) { $scope.dataApi.relation.ok = res_ok; $scope.dataApi.relation.dataArray = (res_referral_id != 0) ? get_res_api_referral.data : []; $scope.dataApi.relation.dataArrayState = res_state; }); }); }); }); /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ /* -- product_staff_id from product/id to txt_staff_id get api staff/id -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.getData().getStaffId(get_res_api_product.data.product_staff_id, function(res_staff) { if (res_staff.status) { $scope.dataApi.staff.dataArrayState = res_state; $scope.dataApi.staff.dataSend.txt_staff_id = res_staff.staff_id; $scope.getData().dataSend($scope.dataApi.staff.api, $scope.dataApi.staff.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, res, res_state) { $scope.dataApi.staff.ok = res_ok; $scope.dataApi.staff.dataArray = res.data; $scope.getData().getNameUrl(res.data.staff_first_name, function(res_staff_first_name_url) { $scope.dataApi.staff.dataArray.staff_first_name_url = res_staff_first_name_url; $scope.dataApi.staff.dataArrayState = res_state; }); }); }); } }); }); /* -- product_staff_id from product/id to txt_staff_id get api staff/id -- */ } else { /* ok = false */ if ($scope.dataApi.product.dataArray.length != 0) { /* product deal to product original */ if ($scope.dataApi.product.dataArray.product_set_array.length != 0) { $scope.countDown().getNameUrl($scope.dataApi.product.dataArray.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", $scope.dataApi.product.dataArray.product_set_array[0].product_id, res_name); }); } else { $scope.pages().pageName("home"); } } else { /* product null */ $scope.pages().pageName("home"); } } }); }); }); }); /* - get api product/id end - */ /* get product api */ }; return promise; });_ui_share_app.directive('productDetailPageT', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageT'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', id: '@id', stilebutton: '@stilebutton', textbutton: '@textbutton', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope._getPostIdFromURL = function() { var dataget = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { dataget = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof dataget === 'number' && dataget > 0) { return dataget; } else { var b = a.split("-"); return b[0]; } }; $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id) { var d = { 'txt_product_id': product_id }; GAEAPI.get('product/id', d).then(function(e) { if (e.ok == 1) { $scope.dataRelate = e.data; console.log("dataRelate", $scope.dataRelate); } }); }; $scope.buildDataProductRelate($scope._getPostIdFromURL()); }; return promise; });_ui_share_app.directive('productDetailPageTsr', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageTsr'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0 }; $scope.login = function() { var login = { showLogin: function() { return UiCustomerBox.delegate.get.isLogin(); }, isLogin: function(callback) { callback(UiCustomerBox.delegate.get.isLogin()); }, pageLogin: function() { var _self = this; _self.isLogin(function(isLogin) { if (!isLogin) { $inloginPopupTypeGrip.open(); } }); } } return login; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); } } } return quantity; }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 1000); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log(name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getDataArrayOk: function(output, callback) { var state = false; if (output.ok == 1) { state = true; callback(output, state); } callback(output, state); }, quantity: function(product_stock_track_type_id, product_total_stock, callback) { var total_stock = 0; /* if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } */ if (product_stock_track_type_id == "0") { total_stock = 20; } else if (product_stock_track_type_id == "1") { if (product_total_stock > 0) { total_stock = product_total_stock; } else { total_stock = 0; } } callback(total_stock); }, main: function() { var _self = this; $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { _self.consoleLog("getDataProductArray : output : ", output.data); _self.getDataArrayOk(output, function(output, state) { if (state) { _self.quantity(output.data.product_stock_track_type_id, output.data.product_total_stock, function(total_stock) { $scope.dataProductBuy.quantity_max = total_stock; _self.consoleLog("getDataProductArray : output : ", output.data); $scope.dataArray = output.data; $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; $scope.dataArrayState = _self.stateData(false, true); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; }); }); } else { $scope.dataArrayState = _self.stateData(false, true); } }); }); } } return data; }; $scope.getDataArray().main(); }; return promise; });_ui_share_app.directive('productDetailPageTypeA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageTypeA'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* getUrlProductId */ $scope.getUrlProductId = function() { $scope.consoleLog("getUrlProductId : $routeParams.product_id : ", $routeParams.product_id); if (typeof $routeParams.product_id !== 'undefined') { var url_product_id = $routeParams.product_id.split("-"); var product_id = url_product_id[0]; return product_id; } }; /* getUrlProductId */ /* consoleLog */ $scope.consoleLog = function(showlog, data) { console.log(showlog, data); }; /* consoleLog */ /* getProductId */ $scope.checkProduct = function() { var cart = { checkOutputOk: function(output, callback) { $scope.consoleLog("cartProduct : cartcCtegory : output : ", output); var output_ok_status = false; if (output.ok == 1) { output_ok_status = true; } callback(output_ok_status); }, saveProduct: function(product, callback) { $scope.consoleLog("cartProduct : cartcCtegory : product : ", product); var save_product = product; callback(save_product); }, checkCtegory: function(category, callback) { $scope.consoleLog("cartProduct : checkCtegory : category : ", category); var ctegory_status = false; if (category.length) { ctegory_status = true; } callback(ctegory_status); }, getCtegoryId: function(category, callback) { $scope.consoleLog("cartProduct : checkCtegory : category : ", category); var referral_id = category[0].referral_id; callback(referral_id); }, getReferralRelationId: function(referral_id, callback) { $scope.consoleLog("cartProduct : getReferralRelationId : referral_id : ", referral_id); var dataSend = { 'txt_referral_id': referral_id }; $scope.consoleLog("cartProduct : getReferralRelationId : dataSend : ", dataSend); GAEAPI.get('referral/relation', dataSend, $scope).then(function(output) { $scope.consoleLog("cartProduct : getReferralRelationId : output : ", output); $scope.checkProduct().checkOutputOk(output, function(output_ok_status) { $scope.consoleLog("cartProduct : getReferralRelationId : checkOutputOk : output_ok_status : ", output_ok_status); var data_relation = false; if (output_ok_status) { $scope.consoleLog("cartProduct : getReferralRelationId : checkOutputOk : ", "PASS"); data_relation = output.data; callback(data_relation); } else { $scope.consoleLog("cartProduct : getReferralRelationId : checkOutputOk : ", "ERROR"); callback(data_relation); } }); }); }, checkStock: function(stock, variant, callback) { $scope.consoleLog("cartProduct : checkStock : stock : ", stock); $scope.consoleLog("cartProduct : checkStock : variant : ", variant); var output_stock = "ERROR"; if (variant == 0) { if (stock == -1) { output_stock = "Do Not Track Inventory"; } else { output_stock = "Track Inventory"; } } else { output_stock = "Attribute Class"; } callback(output_stock); }, calculateStock: function(output_stock, stock, callback) { $scope.consoleLog("cartProduct : calculateStock : output_stock : ", output_stock); $scope.consoleLog("cartProduct : calculateStock : stock : ", stock); var array_stock = []; var number_stock = 0; if (output_stock == "Track Inventory") { if (stock > 20) { stock = 20; } number_stock = stock; for (var i = 0; i < stock; i++) { array_stock.push(i + 1); } } else if (output_stock == "Do Not Track Inventory") { number_stock = 20; for (var i = 0; i < 20; i++) { array_stock.push(i + 1); } } callback(array_stock, number_stock); }, checkAttribute: function(attribute, variant, callback) { $scope.consoleLog("cartProduct : checkAttribute : attribute : ", attribute); $scope.consoleLog("cartProduct : checkAttribute : variant : ", variant); var output_attribute = false; if (attribute.option_data.variant_array.length > 0 && variant > 0) { output_attribute = true; } callback(output_attribute); }, saveAttribute: function(attribute, callback) { $scope.consoleLog("cartProduct : saveAttribute : attribute : ", attribute); var save_attribute = attribute; callback(save_attribute); }, checkPrice: function(product_price, variant, callback) { $scope.consoleLog("cartProduct : checkPrice : attribute : ", attribute); $scope.consoleLog("cartProduct : checkPrice : variant : ", variant); var output_attribute = false; if (attribute.option_data.variant_array.length > 0 && variant > 0) { output_attribute = true; } callback(output_attribute); }, } return cart; }; $scope.dataRelation = false; $scope.dataProduct = false; $scope.dataAttribute = false; $scope.getProductStock = { array: [], number: 0 }; $scope.getProductIdState = { load: true, done: false }; $scope.getProductId = function(product_id) { $scope.consoleLog("getProductId : product_id : ", product_id); $scope.getProductIdState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': product_id }; $scope.consoleLog("getProductId : dataSend : ", dataSend); GAEAPI.get('product/id', dataSend).then(function(output) { $scope.consoleLog("getProductId : get : output : ", output); /* checkOutputOk */ $scope.checkProduct().checkOutputOk(output, function(output_ok_status) { $scope.consoleLog("getProductId : checkOutputOk : output_ok_status : ", output_ok_status); if (output_ok_status) { $scope.consoleLog("getProductId : checkOutputOk : ", "PASS"); /* saveProduct */ $scope.checkProduct().saveProduct(output.data, function(save_product) { $scope.consoleLog("getProductId : saveProduct : save_product : ", save_product); $scope.dataArray = save_product; /* checkCtegory */ $scope.checkProduct().checkCtegory(save_product.product_referral_display.category, function(ctegory_status) { $scope.consoleLog("getProductId : checkCtegory : ctegory_status : ", ctegory_status); if (ctegory_status) { $scope.consoleLog("getProductId : checkCtegory : status : ", "PASS"); $scope.checkProduct().getCtegoryId(save_product.product_referral_display.category, function(referral_id) { $scope.consoleLog("getProductId : checkCtegory : getCtegoryId : referral_id : ", referral_id); $scope.checkProduct().getReferralRelationId(referral_id, function(data_relation) { $scope.consoleLog("getProductId : checkCtegory : getReferralRelationId : data_relation : ", data_relation); $scope.dataRelation = data_relation; }); }); } else { $scope.consoleLog("getProductId : checkCtegory : status : ", "ERROR"); } }); /* checkCtegory */ /* checkStock */ $scope.checkProduct().checkStock(save_product.product_total_stock, save_product.product_total_variant, function(output_stock) { $scope.consoleLog("getProductId : checkStock : output_stock : ", output_stock); $scope.checkProduct().calculateStock(output_stock, save_product.product_total_stock, function(array_stock, number_stock) { $scope.consoleLog("getProductId : calculateStock : array_stock : ", array_stock); $scope.consoleLog("getProductId : calculateStock : number_stock : ", number_stock); $scope.getProductStock.array = array_stock; $scope.getProductStock.number = number_stock; $scope.consoleLog("getProductId : calculateStock : getProductStock : ", $scope.getProductStock); }); }); /* checkStock */ /* checkAttribute */ $scope.checkProduct().checkAttribute(save_product.product_attribute, save_product.product_total_variant, function(output_attribute) { $scope.consoleLog("getProductId : checkAttribute : output_attribute : ", output_attribute); if (output_attribute) { $scope.consoleLog("getProductId : checkAttribute : status : ", "PASS"); $scope.checkProduct().saveAttribute(save_product.product_attribute.option_data.pclass_array, function(save_attribute) { $scope.consoleLog("getProductId : saveAttribute : save_attribute : ", save_attribute); $scope.dataAttribute = save_attribute; $scope.consoleLog("getProductId : saveAttribute : dataAttribute : ", $scope.dataAttribute); }); } else { $scope.consoleLog("getProductId : checkAttribute : status : ", "ERROR"); } }); /* checkAttribute */ }); /* saveProduct */ } else { $scope.consoleLog("getProductId : checkOutputOk : ", "ERROR"); } $scope.getProductIdState = $scope.StateData(false, true); }); /* checkOutputOk */ }); }; /* getProductId */ /* StateData */ $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; /* StateData */ $scope.getProductId($scope.getUrlProductId()); }; return promise; });// _data_qty_modelvar $xZoomTimer = null; // var $xZoomInstance = false; _ui_share_app.directive('productDetailPageU', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageU'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { stylebutton: '@stylebutton', imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.referral_id = '0'; $scope._shop_id = CUR_THEME.shop_id(); $scope._currency = ($scope._shop_id == "635") ? 0 : 2; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; /* JQ: Scroll event */ angular.element($window).bind('scroll', function() { if (!$scope.data) { return; } var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos", curPos, properHeight); if (curPos > properHeight) { angular.element('.block-background .bottom-info').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Slider Send */ $scope.data_min = []; $scope.dataPreserve = false; /* Get product id from url or from component */ $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; /* Get data by product id */ $scope.data = false; $scope._dataArrayState = { load: false, done: false }; $scope.quantity_in = function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.quantity_in(e.data.product_total_stock, function(total_stock) { $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); console.log("product/id : ", $scope.data.product_referral_display); if ($scope.data.product_referral_display.category != undefined) { if ($scope.data.product_referral_display.category.length != 0) { $scope.referral_id = $scope.data.product_referral_display.category[0].referral_id; $scope._getdatamap($scope.data.product_referral_display.category[0].referral_id); } } $scope.show_badge(e.data); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataProductBuy.price = e.data.product_price; $scope.dataProductBuy.sumprice = e.data.product_price; }); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d, $scope).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; // $scope.makeVariantsClick(); $scope.onSelectVariantItems(0, ''); }; $scope.buy_button = false; $scope.dataVariantsPick = []; $scope.max_length = 20; $scope.onSelectVariantItems = function($index, option_id) { $scope.testyuyu = 0; if (option_id == '') { $scope.testyuyu = 0; $scope.buy_button = false; $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); $('.d_qty').removeClass('active').removeClass('inin'); $('.dsetting').addClass("active"); $('.d_qty_not_result').addClass("active"); $scope.dataVariantsPick[$index] = option_id; console.log("check_vareian 1000:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length); return GAEAPI.get('product/id', { 'txt_product_id': $scope._getPostIdFromURL() }, $scope).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; if (e.data.product_attribute.option_data != 0 && e.data.product_total_variant > 0) { if (e.data.product_attribute.option_data.variant_array.length != 0 && e.data.product_total_variant > 0) { var set_varia0 = e.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < e.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseFloat(e.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = e.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = e.data.product_attribute.option_data.variant_array[i]; // $scope.data = $scope.data_min[0]; $scope.data.product_price = $scope.data_min.price; $scope.data.product_compare_price = $scope.data_min.compare_price; } } if ($scope.data_min.length == 0) { $scope.data_min = e.data.product_attribute.option_data.variant_array[0]; $scope.data.product_price = $scope.data_min.price; } console.log("iujdishjdskd : ", $scope.data_min.price); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); } } } }); } else { $scope.dataVariantsPick[$index] = option_id; for (var i = 0; i < $scope.dataVariantsPick.length; i++) { if ($scope.dataVariantsPick[i] != undefined && $scope.dataVariantsPick[i] != "") { $scope.testyuyu++; } } if ($scope.testyuyu >= $scope.dataOption.length) { $scope.testyuyu = 0; $('.d_qty_not_result').removeClass("active"); $('.dsetting').removeClass("active"); $scope.findVariantsData($scope.dataVariantsPick); $scope.buy_button = true; } else { $scope.testyuyu = 0; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); } console.log("check_vareian 1001:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length, $scope.electric); } }; $scope.findVariantsData = function(variantsPick) { var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; $scope.data.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count); // $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = 0; $scope.data.product_compare_price = 0; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $timeout.cancel(s); $('select.variantSelector').each(function(idx, obj) { var optionElementFirst = $(this).find('option[data-index="' + idx + '"]').eq(0); optionElementFirst.prop("selected", true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original = 1; $scope.qty_current = 1; $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; $scope.gallerySingleViewIndex = 0; $scope.switchSingleView = function(idx) { console.log("$xZoomInstance", $xZoomInstance); $('.gallery_show_single').css({ 'transition': 'all 0.3s', 'opacity': '0' }); $timeout(function() { $scope.gallerySingleViewIndex = idx; $('.gallery_show_single').css({ 'opacity': '1' }); }, 300); setTimeout(function() { if ($(window).width() >= 992) { if ($("img.zoom").attr('data-api-width') > 400 && $("img.zoom").attr('data-api-height') > 400) { /*$("img.zoom").ezPlus({ 'scrollZoom':true, 'responsive':true, 'zoomWindowWidth':400, 'zoomWindowHeight':400, 'zoomWindowOffetx':30, });*/ $xZoomInstance = $('.zoom').xzoom({ Xoffset: 30, tint: '#b9b5b3', }); } } }, 300); }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; $scope.datamap = []; $scope._getdatamap = function(dataIn) { var dataSend = { 'txt_referral_id': dataIn }; GAEAPI.get('referral/relation', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope.datamap = output.data; } }); } $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity_max; } _self.upDatePrice(); _self.quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); _self.quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity; _self.upDatePrice(); _self.quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity; _self.upDatePrice(); _self.quantityBreaks(); } }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.data, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } } } return quantity; }; $scope._data_qty_model = 1; $scope.viewQuantity = function() { return $(".qty_display").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; }; $scope.warning_qty = 0; $scope.getWarn_qty = function() { $scope.warning_qty = 1; }; $scope.ShowWithBadge = false; $scope.show_badge = function(data) { if (data.product_badge.length > 0) { for (var i = 0; i < data.product_badge.length; i++) { if (data.product_badge[i].badge_id == 18) { $scope.ShowWithBadge = true; break; } } } else { $scope.ShowWithBadge = false; } } }; return promise; });var $xZoomTimer = null; var $xZoomInstance = false; _ui_share_app.directive('productDetailPageUa', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageUa'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { stylebutton: '@stylebutton', imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; /* JQ: Scroll event */ angular.element($window).bind('scroll', function() { if (!$scope.data) { return; } var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos", curPos, properHeight); if (curPos > properHeight) { angular.element('.block-background .bottom-info').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* Slider Send */ $scope.data_min = []; $scope.dataPreserve = false; $scope.names = []; /* Get product id from url or from component */ $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; /* Get data by product id */ $scope.data = false; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.getRelation($scope.data.product_referral[0].referral_id); $scope._getdatamap($scope.data.product_referral_display.category[0].referral_id); $scope.show_badge(e.data); $scope.timeCountStart2(e.data); if(e.data.product_total_variant == 0 && e.data.product_total_stock > 0){ $scope.names = []; for (var i = 0; i < parseInt(e.data.product_total_stock); i++) { $scope.names.push(i+1); } console.log("nnames stock :",$scope.names); } if(e.data.product_total_variant == 0 && e.data.product_total_stock < 0){ $scope.names = []; for (var i = 0; i < 10; i++) { $scope.names.push(i+1); } console.log("nnames stock :",$scope.names); } if(e.data.product_total_variant > 0){ $scope.names = []; for (var i = 0; i < 10; i++) { $scope.names.push(i+1); } } } console.log("detail_id_npd : ",$scope.data); $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope.showPart = ""; $scope.showPart_wan = ""; $scope.showPart_h = ""; $scope.showPart_m = ""; $scope.showPart_s = ""; $scope.countDown = function(settime) { var time_year = ""; var time_mount = ""; var time_date = ""; var time_hr = ""; var time_mi = ""; var time_se = ""; var timeA = ""; var timeB = ""; var timeC = ""; var timeDifference = ""; var timeDifference_temp = ""; var wan = ""; var l_wan = ""; var hour = ""; var l_hour = ""; var minute = ""; var second = ""; time_year = GAEAPI.time.dateFormat("YYYY", settime.product_lifetime.lifetime_end_time); time_mount = GAEAPI.time.dateFormat("M", settime.product_lifetime.lifetime_end_time); time_date = GAEAPI.time.dateFormat("D", settime.product_lifetime.lifetime_end_time); time_hr = GAEAPI.time.dateFormat("H", settime.product_lifetime.lifetime_end_time); time_mi = GAEAPI.time.dateFormat("m", settime.product_lifetime.lifetime_end_time); time_se = GAEAPI.time.dateFormat("s", settime.product_lifetime.lifetime_end_time); timeA = new Date(); /* วันเวลาปัจจุบัน */ timeB = new Date(time_year, (time_mount - 1), time_date, time_hr, time_mi, time_se, '0'); timeDifference = timeB.getTime() - timeA.getTime(); console.log("timeDifference", timeDifference); if (timeDifference >= 0) { timeDifference = timeDifference / 1000; timeDifference = Math.floor(timeDifference); wan = Math.floor(timeDifference / 86400); l_wan = timeDifference % 86400; hour = Math.floor(l_wan / 3600); l_hour = l_wan % 3600; minute = Math.floor(l_hour / 60); second = l_hour % 60; $scope.showPart = wan + " วัน " + pad(hour, 2) + " ชั่วโมง " + pad(minute, 2) + " นาที " + pad(second, 2) + " วินาที"; $scope.showPart_wan = wan; $scope.showPart_h = pad(hour, 2); $scope.showPart_m = pad(minute, 2); $scope.showPart_s = pad(second, 2); if (wan == 0 && hour == 0 && minute == 0 && second == 0) {} console.log("check_array", $scope.showPart); } }; function pad(str, max) { str = str.toString(); return str.length < max ? pad("0" + str, max) : str; }; $scope.timeout_promise2 = null; $scope.timeCountStart2 = function(settime) { $scope.timeout_promise2 = $timeout(function() { $scope.countDown(settime); $scope.timeCountStart2(settime); }, 1000); }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d, $scope).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; // $scope.makeVariantsClick(); $scope.onSelectVariantItems(0, ''); }; $scope.buy_button = false; $scope.dataVariantsPick = []; $scope.max_length = 20; $scope.onSelectVariantItems = function($index, option_id) { $scope.testyuyu = 0; if (option_id == '') { $scope.testyuyu = 0; $scope.buy_button = false; $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); $('.d_qty').removeClass('active').removeClass('inin'); $('.dsetting').addClass("active"); $('.d_qty_not_result').addClass("active"); $scope.dataVariantsPick[$index] = option_id; console.log("check_vareian 1000:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length); return GAEAPI.get('product/id', { 'txt_product_id': $scope._getPostIdFromURL() }, $scope).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; if (e.data.product_attribute.option_data != 0 && e.data.product_total_variant > 0) { if (e.data.product_attribute.option_data.variant_array.length != 0 && e.data.product_total_variant > 0) { var set_varia0 = e.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < e.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(e.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = e.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = e.data.product_attribute.option_data.variant_array[i]; // $scope.data = $scope.data_min[0]; $scope.data.product_price = $scope.data_min.price; $scope.data.product_compare_price = $scope.data_min.compare_price; } } if ($scope.data_min.length == 0) { $scope.data_min = e.data.product_attribute.option_data.variant_array[0]; $scope.data.product_price = $scope.data_min.price; } console.log("iujdishjdskd : ", $scope.data_min.price); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); } } } }); } else { $scope.dataVariantsPick[$index] = option_id; for (var i = 0; i < $scope.dataVariantsPick.length; i++) { if ($scope.dataVariantsPick[i] != undefined && $scope.dataVariantsPick[i] != "") { $scope.testyuyu++; } } if ($scope.testyuyu >= $scope.dataOption.length) { $scope.testyuyu = 0; $('.d_qty_not_result').removeClass("active"); $('.dsetting').removeClass("active"); $scope.findVariantsData($scope.dataVariantsPick); $scope.buy_button = true; } else { $scope.testyuyu = 0; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); } console.log("check_vareian 1001:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length, $scope.electric); } }; $scope.findVariantsData = function(variantsPick) { var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; $scope.data.product_total_stock = dataVariants[i].total_stock; $scope.names = []; for (var j = 0; j < 10; j++) { $scope.names.push(j+1); } $scope.max_length = dataVariants[i].total_stock; break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count); // $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = 0; $scope.data.product_compare_price = 0; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $timeout.cancel(s); $('select.variantSelector').each(function(idx, obj) { var optionElementFirst = $(this).find('option[data-index="' + idx + '"]').eq(0); optionElementFirst.prop("selected", true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original = 1; $scope.qty_current = 1; $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; $scope.gallerySingleViewIndex = 0; $scope.switchSingleView = function(idx) { console.log("$xZoomInstance", $xZoomInstance); $('.gallery_show_single').css({ 'transition': 'all 0.3s', 'opacity': '0' }); $timeout(function() { $scope.gallerySingleViewIndex = idx; $('.gallery_show_single').css({ 'opacity': '1' }); }, 300); setTimeout(function() { if ($(window).width() >= 992) { if ($("img.zoom").attr('data-api-width') > 400 && $("img.zoom").attr('data-api-height') > 400) { /*$("img.zoom").ezPlus({ 'scrollZoom':true, 'responsive':true, 'zoomWindowWidth':400, 'zoomWindowHeight':400, 'zoomWindowOffetx':30, });*/ $xZoomInstance = $('.zoom').xzoom({ Xoffset: 30, tint: '#b9b5b3', }); } } }, 300); }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; $scope.redirectCheckout = function(p,q){ window.location.href = GURL.base_url() + "checkout?pdata="+p+'-'+q; }; $scope.datamap = []; $scope._getdatamap = function(dataIn) { var dataSend = { 'txt_referral_id': dataIn }; GAEAPI.get('referral/relation', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope.datamap = output.data; } }); } $scope._data_qty_model = 1; $scope.viewQuantity = function() { var check_num = 1; if($(".d_qty_i").find('select').val() != undefined && $(".d_qty_i").find('select').val() != ''){ check_num = $(".d_qty_i").find('select').val().substr(7); }else{ $(".d_qty_i").find('select').val("number:1"); $(".d_qty_i").find('select').selectedIndex = "2"; } console.log("shdgshdgsh :",check_num); return parseInt(check_num); // return $(".qty_display").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 9) { i = 9; } if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('select[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('select[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt($('#detail_qty[variant-key="' + variant_key + '"]').val().substr(7)); // alert(i); console.log("data_set array test : ",i); $scope._data_qty_selected = i; // parseInt(e.val()); // alert(i); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; alert("กรุณาเลือกตัวเลือกให้ครบถ้วน"); }; $scope.warning_qty = 0; $scope.getWarn_qty = function() { $scope.warning_qty = 1; }; $scope.ShowWithBadge = false; $scope.show_badge = function(data) { if (data.product_badge.length > 0) { for (var i = 0; i < data.product_badge.length; i++) { if (data.product_badge[i].badge_id == 18) { $scope.ShowWithBadge = true; break; } } } else { $scope.ShowWithBadge = false; } } }; return promise; });var $xZoomTimer = null; var $xZoomInstance = false; _ui_share_app.directive('productDetailPageUb', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageUb'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name' }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayTags = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.showTab = { activeTab: 'description', dataTab: [{ en: 'description', th: 'รายละเอียดสินค้า', data: '' }, { en: 'info', th: 'วิธีการชำระเงินและวิธีการจัดส่ง', data: '' }] }; $scope.attribute = { state: false, attributeOption: [], variants: 'description', variantsPick: [], dataVariants: [], variantsTotal: 0 }; $scope.buy = { state: false, attribute: false }; $scope.processBuy = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, onClickFalse: function() { if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } } } return functionIn; }; $scope.attributeOption = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, checkVariantsPick: function(variantsPick) { if (variantsPick.length != 0) { var state = 0; for (var i = 0; i < variantsPick.length; i++) { if (variantsPick[i] == "") { state = state + 1; } } if (state == 0) { return true } else { return false } } else { return false } }, compareArray: function(attributeOption, optionJson) { if (!optionJson) return false; if (attributeOption.length != optionJson.length) return false; for (var i = 0, l = attributeOption.length; i < l; i++) { if (attributeOption[i] instanceof Array && optionJson[i] instanceof Array) { if (!compareArray(attributeOption[i], optionJson[i])) return false; } else if (attributeOption[i] != optionJson[i]) { return false; } } return true; }, findVariantsData: function(attributeOption, dataVariants, callback) { var _self = this; var variants = dataVariants; _self.consoleLog("findVariantsData : variants : ", variants); var variantsOut = []; for (var i = 0; i < variants.length; i++) { var optionJson = angular.fromJson(variants[i].option_id_json); if (_self.compareArray(attributeOption, optionJson)) { _self.consoleLog("findVariantsData : variants[i] : ", variants[i]); variantsOut = variants[i]; break; } } callback(variantsOut); }, checkOption: function(variants_total, callback) { var state = false; if (variants_total == 0) { state = true; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = false; if (stateIn == false && quantity_max > 0) { state = true; } callback(state); }, onClickOption: function($index, option_id) { var _self = this; _self.consoleLog("onClickOption : index : ", $index); _self.consoleLog("onClickOption : option_id : ", option_id); $scope.attribute.variantsPick[$index] = option_id; _self.consoleLog("onClickOption : $scope.attribute.variantsPick[$index] : ", $scope.attribute.variantsPick[$index]); if ($scope.attribute.attributeOption.length >= $scope.attribute.variantsPick.length) { if (_self.checkVariantsPick($scope.attribute.variantsPick)) { _self.consoleLog("onClickOption : if : $scope.attribute.attributeOption.length : ", $scope.attribute.attributeOption.length); _self.consoleLog("onClickOption : if : $scope.attribute.variantsPick.length : ", $scope.attribute.variantsPick.length); _self.findVariantsData($scope.attribute.variantsPick, $scope.attribute.dataVariants, function(variantsOut) { _self.consoleLog("onClickOption : if : findVariantsData : variantsOut : ", variantsOut); $scope.dataArray.product_id = variantsOut.product_id; $scope.dataArray.product_sku = variantsOut.sku; $scope.dataArray.product_price = variantsOut.price; $scope.dataArray.product_compare_price = variantsOut.compare_price; $scope.dataProductBuy.quantity_max = variantsOut.total_stock; _self.checkOption($scope.attribute.variantsTotal, function(state) { _self.checkTotalStock(state, variantsOut.total_stock, function(state) { $scope.buy.state = state; if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } }); }); $scope.quantity().input(); }); } } } } return functionIn; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity_max; } _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } } } return quantity; }; $scope.carouselId = ''; $scope.slickCarouselId = function() { if ($scope.carouselId == '') { $scope.carouselId = Math.floor((Math.random() * 9999) + 1000); return $scope.carouselId; } else { return $scope.carouselId; } }; $scope.slickImageGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope.carouselId + '"]').slick('slickGoTo', idx); }, 100); }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 1000); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log(name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getQuantityBreak: function(api, callback) { var _self = this; _self.getProductId(function(product_id) { var customerId = 0; if (UiCustomerBox.delegate.get.isLogin()) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); } var dataSendQuantityBreak = { 'txt_product_id': product_id, 'txt_customer_id': customerId }; var quantity_break = []; _self.getDataArray(api, dataSendQuantityBreak, function(output) { if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); }); }, quantity: function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.dataArray, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } }, showTab: function(input, callback) { var description = input.product_description; var info = input.product_more_info; callback(description, info); }, productTab: function(product_tags, callback) { var _self = this; _self.consoleLog("productTab : product_tags : ", product_tags); var productTab = []; if (product_tags != undefined) { if (product_tags != "") { productTab = product_tags.split(","); callback(productTab); } else { callback(productTab); } } else { callback(productTab); } }, getAttribute: function(input, callback) { var _self = this; var attribute = []; var variants = []; var variants_total = 0; _self.consoleLog("getAttribute : input : ", input); if (input.product_attribute.option_data !== 'undefined' && input.product_total_variant > 0) { _self.consoleLog("getAttribute : input.product_attribute.option_data : ", input.product_attribute.option_data); _self.consoleLog("getAttribute : input.product_total_variant : ", input.product_total_variant); if (input.product_attribute.option_data.pclass_array !== 'undefined' && input.product_attribute.option_data.pclass_array.length) { _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array : ", input.product_attribute.option_data.pclass_array); _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array.length : ", input.product_attribute.option_data.pclass_array.length); attribute = input.product_attribute.option_data.pclass_array; variants = input.product_attribute.option_data.variant_array; variants_total = input.product_total_variant; } } callback(variants_total, attribute, variants); }, checkOption: function(variants_total, callback) { var state = false; if (variants_total == 0) { state = true; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = false; if (stateIn == true && quantity_max > 0) { state = true; } callback(state); }, main: function() { var _self = this; $scope.slickCarouselId(); $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { _self.consoleLog("getDataProductArray : output : ", output.data); _self.quantity(output.data.product_total_stock, function(total_stock) { _self.consoleLog("quantity : total_stock : ", total_stock); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataArray = output.data; _self.productTab(output.data.product_tags, function(productTab) { $scope.dataArrayTags = productTab; _self.showTab(output.data, function(description, info) { $scope.showTab.dataTab[0].data = description; $scope.showTab.dataTab[1].data = info; }); _self.getAttribute(output.data, function(variants_total, attribute, variants) { _self.consoleLog("getAttribute : variants_total : ", variants_total); _self.consoleLog("getAttribute : attribute : ", attribute); _self.consoleLog("getAttribute : variants : ", variants); _self.checkOption(variants_total, function(state) { _self.checkTotalStock(state, total_stock, function(state) { $scope.buy.state = state; $scope.attribute.attributeOption = attribute; $scope.attribute.dataVariants = variants; $scope.attribute.variantsTotal = variants_total; }); }); }); $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; _self.getQuantityBreak('product/quantity_break', function(quantity_break) { _self.consoleLog("getQuantityBreak : output : ", quantity_break); $scope.dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.dataProductBuy.result_price = quantity_break[0].unit_price; } }); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; $scope.dataArrayState = _self.stateData(false, true); }); }); }); }); } } return data; }; $scope.getDataArray().main(); }; return promise; });var $xZoomTimer = null; var $xZoomInstance = false; _ui_share_app.directive('productDetailPageUc', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageUc'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', icon : '@icon', stylebutton : '@stylebutton' }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayTags = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.showTab = { activeTab: 'description', dataTab: [{ en: 'description', th: 'รายละเอียดสินค้า', data: '' }, { en: 'info', th: 'วิธีการชำระเงินและวิธีการจัดส่ง', data: '' }] }; $scope.attribute = { state: false, attributeOption: [], variants: 'description', variantsPick: [], dataVariants: [], variantsTotal: 0 }; $scope.buy = { state: false, attribute: false }; $scope.processBuy = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, onClickFalse: function() { if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } } } return functionIn; }; $scope.attributeOption = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, checkVariantsPick: function(variantsPick) { if (variantsPick.length != 0) { var state = 0; for (var i = 0; i < variantsPick.length; i++) { if (variantsPick[i] == "") { state = state + 1; } } if (state == 0) { return true } else { return false } } else { return false } }, compareArray: function(attributeOption, optionJson) { if (!optionJson) return false; if (attributeOption.length != optionJson.length) return false; for (var i = 0, l = attributeOption.length; i < l; i++) { if (attributeOption[i] instanceof Array && optionJson[i] instanceof Array) { if (!compareArray(attributeOption[i], optionJson[i])) return false; } else if (attributeOption[i] != optionJson[i]) { return false; } } return true; }, findVariantsData: function(attributeOption, dataVariants, callback) { var _self = this; var variants = dataVariants; _self.consoleLog("findVariantsData : variants : ", variants); var variantsOut = []; for (var i = 0; i < variants.length; i++) { var optionJson = angular.fromJson(variants[i].option_id_json); if (_self.compareArray(attributeOption, optionJson)) { _self.consoleLog("findVariantsData : variants[i] : ", variants[i]); variantsOut = variants[i]; break; } } callback(variantsOut); }, checkOption: function(variants_total, callback) { var state = false; if (variants_total == 0) { state = true; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = false; if (stateIn == false && quantity_max > 0) { state = true; } callback(state); }, onClickOption: function($index, option_id) { var _self = this; _self.consoleLog("onClickOption : index : ", $index); _self.consoleLog("onClickOption : option_id : ", option_id); $scope.attribute.variantsPick[$index] = option_id; _self.consoleLog("onClickOption : $scope.attribute.variantsPick[$index] : ", $scope.attribute.variantsPick[$index]); if ($scope.attribute.attributeOption.length >= $scope.attribute.variantsPick.length) { if (_self.checkVariantsPick($scope.attribute.variantsPick)) { _self.consoleLog("onClickOption : if : $scope.attribute.attributeOption.length : ", $scope.attribute.attributeOption.length); _self.consoleLog("onClickOption : if : $scope.attribute.variantsPick.length : ", $scope.attribute.variantsPick.length); _self.findVariantsData($scope.attribute.variantsPick, $scope.attribute.dataVariants, function(variantsOut) { _self.consoleLog("onClickOption : if : findVariantsData : variantsOut : ", variantsOut); $scope.dataArray.product_id = variantsOut.product_id; $scope.dataArray.product_sku = variantsOut.sku; $scope.dataArray.product_price = variantsOut.price; $scope.dataArray.product_compare_price = variantsOut.compare_price; $scope.dataProductBuy.quantity_max = variantsOut.total_stock; _self.checkOption($scope.attribute.variantsTotal, function(state) { _self.checkTotalStock(state, variantsOut.total_stock, function(state) { $scope.buy.state = state; if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } }); }); $scope.quantity().input(); }); } } } } return functionIn; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = $scope.dataProductBuy.quantity_max; } _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } } } return quantity; }; $scope.carouselId = ''; $scope.slickCarouselId = function() { if ($scope.carouselId == '') { $scope.carouselId = Math.floor((Math.random() * 9999) + 1000); return $scope.carouselId; } else { return $scope.carouselId; } }; $scope.slickImageGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope.carouselId + '"]').slick('slickGoTo', idx); }, 100); }; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 1000); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log(name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getQuantityBreak: function(api, callback) { var _self = this; _self.getProductId(function(product_id) { var customerId = 0; if (UiCustomerBox.delegate.get.isLogin()) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); } var dataSendQuantityBreak = { 'txt_product_id': product_id, 'txt_customer_id': customerId }; var quantity_break = []; _self.getDataArray(api, dataSendQuantityBreak, function(output) { if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); }); }, quantity: function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 20; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.dataArray, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } }, showTab: function(input, callback) { var description = input.product_description; var info = input.product_more_info; callback(description, info); }, productTab: function(product_tags, callback) { var _self = this; _self.consoleLog("productTab : product_tags : ", product_tags); var productTab = []; if (product_tags != undefined) { if (product_tags != "") { productTab = product_tags.split(","); callback(productTab); } else { callback(productTab); } } else { callback(productTab); } }, getAttribute: function(input, callback) { var _self = this; var attribute = []; var variants = []; var variants_total = 0; _self.consoleLog("getAttribute : input : ", input); if (input.product_attribute.option_data !== 'undefined' && input.product_total_variant > 0) { _self.consoleLog("getAttribute : input.product_attribute.option_data : ", input.product_attribute.option_data); _self.consoleLog("getAttribute : input.product_total_variant : ", input.product_total_variant); if (input.product_attribute.option_data.pclass_array !== 'undefined' && input.product_attribute.option_data.pclass_array.length) { _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array : ", input.product_attribute.option_data.pclass_array); _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array.length : ", input.product_attribute.option_data.pclass_array.length); attribute = input.product_attribute.option_data.pclass_array; variants = input.product_attribute.option_data.variant_array; variants_total = input.product_total_variant; } } callback(variants_total, attribute, variants); }, checkOption: function(variants_total, callback) { var state = false; if (variants_total == 0) { state = true; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = false; if (stateIn == true && quantity_max > 0) { state = true; } callback(state); }, main: function() { var _self = this; $scope.slickCarouselId(); $scope.dataArrayState = _self.stateData(true, false); _self.getDataProductArray('product/id', function(output) { _self.consoleLog("getDataProductArray : output : ", output.data); _self.quantity(output.data.product_total_stock, function(total_stock) { _self.consoleLog("quantity : total_stock : ", total_stock); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataArray = output.data; _self.productTab(output.data.product_tags, function(productTab) { $scope.dataArrayTags = productTab; _self.showTab(output.data, function(description, info) { $scope.showTab.dataTab[0].data = description; $scope.showTab.dataTab[1].data = info; }); _self.getAttribute(output.data, function(variants_total, attribute, variants) { _self.consoleLog("getAttribute : variants_total : ", variants_total); _self.consoleLog("getAttribute : attribute : ", attribute); _self.consoleLog("getAttribute : variants : ", variants); _self.checkOption(variants_total, function(state) { _self.checkTotalStock(state, total_stock, function(state) { $scope.buy.state = state; $scope.attribute.attributeOption = attribute; $scope.attribute.dataVariants = variants; $scope.attribute.variantsTotal = variants_total; }); }); }); $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; _self.getQuantityBreak('product/quantity_break', function(quantity_break) { _self.consoleLog("getQuantityBreak : output : ", quantity_break); $scope.dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.dataProductBuy.result_price = quantity_break[0].unit_price; } }); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; $scope.dataArrayState = _self.stateData(false, true); }); }); }); }); } } return data; }; $scope.getDataArray().main(); }; return promise; });var $xZoomTimer = null; var $xZoomInstance = false; _ui_share_app.directive('productDetailPageUd', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailPageUd'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', icon: '@icon', stylebutton: '@stylebutton' }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.shopPointConfig = []; $scope.navigationBar = []; $scope.dataArray = []; $scope.dataArrayTags = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataProductBuy = { inputQuantity: 1, quantity: 1, price: 0, sumprice: 0, quantity_min: 0, quantity_max: 0, result_price: 0 }; $scope.showTab = { activeTab: 'description', dataTab: [{ en: 'description', th: 'รายละเอียดสินค้า', data: '' }, { en: 'info', th: 'วิธีการชำระเงินและวิธีการจัดส่ง', data: '' }] }; $scope.attribute = { state: false, attributeOption: [], variants: 'description', variantsPick: [], dataVariants: [], variantsTotal: 0 }; $scope.buy = { state: false, attribute: false }; $scope.processBuy = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, onClickFalse: function() { if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } } } return functionIn; }; $scope.attributeOption = function() { var functionIn = { consoleLog: function(name, data) { console.log(name, data); }, checkVariantsPick: function(variantsPick) { if (variantsPick.length != 0) { var state = 0; for (var i = 0; i < variantsPick.length; i++) { if (variantsPick[i] == "") { state = state + 1; } } if (state == 0) { return true } else { return false } } else { return false } }, compareArray: function(attributeOption, optionJson) { if (!optionJson) return false; if (attributeOption.length != optionJson.length) return false; for (var i = 0, l = attributeOption.length; i < l; i++) { if (attributeOption[i] instanceof Array && optionJson[i] instanceof Array) { if (!compareArray(attributeOption[i], optionJson[i])) return false; } else if (attributeOption[i] != optionJson[i]) { return false; } } return true; }, checkAttributeOption: function(attributeOption, attributeOptionLength, callback) { var _self = this; var attribute = (attributeOption.length == attributeOptionLength) ? true : false; for (var i = 0; i < attributeOption.length; i++) { _self.consoleLog("checkAttributeOption : attributeOption[i] : ", attributeOption[i]); if (attributeOption[i] == undefined) { attribute = false; } } callback(attribute); }, findVariantsData: function(attributeOption, dataVariants, attributeOptionLength, callback) { var _self = this; _self.consoleLog("findVariantsData : attributeOption : ", attributeOption); _self.consoleLog("findVariantsData : dataVariants : ", dataVariants); _self.consoleLog("findVariantsData : attributeOptionLength : ", attributeOptionLength); _self.checkAttributeOption(attributeOption, attributeOptionLength, function(res_attribute_option) { _self.consoleLog("checkAttributeOption : callback : res_attribute_option ", res_attribute_option); var variantsOut = []; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (_self.compareArray(attributeOption, optionJson)) { _self.consoleLog("findVariantsData : dataVariants[i] : ", dataVariants[i]); variantsOut = dataVariants[i]; break; } } callback(variantsOut, res_attribute_option); }); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var _self = this; var state = true; _self.consoleLog("checkTotalStock : index : ", stateIn); _self.consoleLog("checkTotalStock : quantity_max : ", quantity_max); if (stateIn == false && quantity_max > 0) { state = false; } callback(state); }, onClickOption: function($index, option_id) { var _self = this; _self.consoleLog("onClickOption : index : ", $index); _self.consoleLog("onClickOption : option_id : ", option_id); $scope.attribute.variantsPick[$index] = option_id; _self.consoleLog("onClickOption : $scope.attribute.variantsPick[$index] : ", $scope.attribute.variantsPick[$index]); if ($scope.attribute.attributeOption.length >= $scope.attribute.variantsPick.length) { if (_self.checkVariantsPick($scope.attribute.variantsPick)) { _self.consoleLog("onClickOption : if : $scope.attribute.attributeOption.length : ", $scope.attribute.attributeOption.length); _self.consoleLog("onClickOption : if : $scope.attribute.variantsPick.length : ", $scope.attribute.variantsPick.length); _self.findVariantsData($scope.attribute.variantsPick, $scope.attribute.dataVariants, $scope.attribute.attributeOption.length, function(variantsOut, res_attribute_option) { _self.consoleLog("onClickOption : if : findVariantsData : variantsOut : ", variantsOut); _self.consoleLog("onClickOption : if : findVariantsData : res_attribute_option : ", res_attribute_option); if (variantsOut.length != 0 && res_attribute_option) { $scope.dataArray.product_id = variantsOut.product_id; $scope.dataArray.product_sku = variantsOut.sku; $scope.dataProductBuy.price = variantsOut.price; $scope.dataArray.product_compare_price = variantsOut.compare_price; $scope.dataProductBuy.quantity_max = variantsOut.total_stock; _self.consoleLog("zzzz onClickOption : variantsOut : ", variantsOut); _self.consoleLog("zzzz onClickOption : variantsOut : ", $scope.dataArray.product_image); if (variantsOut.variant_image != 0) { if ($scope.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataArray.product_image.length; i++) { if ($scope.dataArray.product_image[i].image_id == variantsOut.variant_image[0].image_id) { $scope.slickImageGoto(variantsOut.variant_image[0].image_id); } } } } _self.checkOption($scope.attribute.variantsTotal, function(state) { _self.checkTotalStock(state, variantsOut.total_stock, function(state) { $scope.buy.state = state; if ($scope.attribute.variantsTotal != 0) { $scope.buy.attribute = true; } }); }); } else if (variantsOut.length == 0 && res_attribute_option) { $scope.dataArray.product_id = 0; $scope.dataArray.product_sku = ''; $scope.dataProductBuy.price = 0; $scope.dataArray.product_compare_price = 0; $scope.dataProductBuy.quantity_max = 1; $scope.buy.state = true; $scope.buy.attribute = true; } $scope.quantity().input(); }); } } } } return functionIn; }; $scope.quantity = function() { var quantity = { upDatePrice: function() { $scope.dataProductBuy.sumprice = $scope.dataProductBuy.price * $scope.dataProductBuy.quantity; }, input: function() { var _self = this; if ($scope.dataProductBuy.inputQuantity > 0) { console.log("quantity : input : inputQuantity : ", $scope.dataProductBuy.inputQuantity); console.log("quantity : input : quantity_max : ", $scope.dataProductBuy.quantity_max); if ($scope.dataProductBuy.inputQuantity <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.inputQuantity; } else { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity_max; $scope.dataProductBuy.inputQuantity = ($scope.dataProductBuy.quantity_max != 0) ? $scope.dataProductBuy.quantity_max : 1; } _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } else { console.log("quantity : input : ", $scope.dataProductBuy.inputQuantity); if ($scope.dataProductBuy.inputQuantity <= 0) { $scope.dataProductBuy.quantity = 1; } else { $scope.dataProductBuy.inputQuantity = 1; $scope.dataProductBuy.quantity = 1; } /* $scope.dataProductBuy.quantity = 1; $scope.dataProductBuy.inputQuantity = 1; */ _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, minus: function() { var _self = this; if (($scope.dataProductBuy.quantity - 1) != $scope.dataProductBuy.quantity_min) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity - 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } }, plus: function() { var _self = this; if (($scope.dataProductBuy.quantity + 1) <= $scope.dataProductBuy.quantity_max) { $scope.dataProductBuy.quantity = $scope.dataProductBuy.quantity + 1; _self.upDatePrice(); $scope.getDataArray().quantityBreaks(); } } } return quantity; }; $scope.carouselId = ''; $scope.slickCarouselId = function() { if ($scope.carouselId == '') { $scope.carouselId = Math.floor((Math.random() * 9999) + 1000); return $scope.carouselId; } else { return $scope.carouselId; } }; $scope.slickImageGoto = function(idx) { $scope.cover_lists_index = idx; setTimeout(function() { $scope.cover_lists_index = idx; // $('[data-key="' + $scope.carouselId + '"]').slick('slickGoTo', idx); }, 100); }; $scope.cover_lists_index = 0; $scope.imageCarousel = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 1000); }; $scope.imageCarouselBar = function(cover_in, carousel_in) { $(cover_in).css('height', '0'); $(cover_in).css('opacity', '0'); setTimeout(function() { var carousel = $(carousel_in); carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: false, autoplaySpeed: 4000, infinite: true, slidesToShow: 6, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 5, } }, { breakpoint: 991, settings: { slidesToShow: 4, } }, { breakpoint: 767, settings: { slidesToShow: 3, } }] }).closest('section').addClass('active'); $(cover_in).css('height', 'auto'); $(cover_in).css('opacity', '1'); }, 1000); }; $scope.getDataArray = function() { var data = { consoleLog: function(name, data) { console.log(name, data); }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, getProductId: function(callback) { var params = $routeParams; var product_id = params.product_id.split("-", 1).join(""); callback(product_id) }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(res) { _self.consoleLog("getData : res : ", res); callback(res); }); }, getDataProductArray: function(api, callback) { var _self = this; var output = []; _self.getProductId(function(product_id) { var dataSendProductId = { 'txt_product_id': product_id }; _self.getDataArray(api, dataSendProductId, function(output) { callback(output); }); }); }, getNavigationBar: function(product_referral_display, api, callback) { var _self = this; var output = []; _self.consoleLog("product_referral_display : ", product_referral_display); if (product_referral_display.category.length != 0) { var dataSendReferralId = { 'txt_referral_id': product_referral_display.category[0].referral_id }; _self.getDataArray(api, dataSendReferralId, function(output) { callback(output); }); } else { callback(output); } }, getDataArray: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, getQuantityBreak: function(api, callback) { var _self = this; _self.getProductId(function(product_id) { var customerId = 0; if (UiCustomerBox.delegate.get.isLogin()) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); } var dataSendQuantityBreak = { 'txt_product_id': product_id, 'txt_customer_id': customerId }; var quantity_break = []; _self.getDataArray(api, dataSendQuantityBreak, function(output) { if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); }); }, quantity: function(product_total_stock, callback) { var total_stock = 0; if (product_total_stock == -1) { total_stock = 9999; } else if (product_total_stock != -1 && product_total_stock != 0) { total_stock = product_total_stock; } callback(total_stock); }, quantityBreaks: function() { var _self = this; var productQuantityBreak = GAEAPI.getValueForKey($scope.dataArray, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope.data, "product_price", 0); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if ($scope.dataProductBuy.quantity >= amount_end) { $scope.dataProductBuy.result_price = unit_price; } } }, showTab: function(input, callback) { var description = input.product_description; var info = input.product_more_info; callback(description, info); }, productTab: function(product_tags, callback) { var _self = this; _self.consoleLog("productTab : product_tags : ", product_tags); var productTab = []; if (product_tags != undefined) { if (product_tags != "") { productTab = product_tags.split(","); callback(productTab); } else { callback(productTab); } } else { callback(productTab); } }, getAttribute: function(input, callback) { var _self = this; var attribute = []; var variants = []; var variants_total = 0; _self.consoleLog("getAttribute : input : ", input); if (input.product_attribute.option_data !== 'undefined' && input.product_total_variant > 0) { _self.consoleLog("getAttribute : input.product_attribute.option_data : ", input.product_attribute.option_data); _self.consoleLog("getAttribute : input.product_total_variant : ", input.product_total_variant); if (input.product_attribute.option_data.pclass_array !== 'undefined' && input.product_attribute.option_data.pclass_array.length) { _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array : ", input.product_attribute.option_data.pclass_array); _self.consoleLog("getAttribute : input.product_attribute.option_data.pclass_array.length : ", input.product_attribute.option_data.pclass_array.length); attribute = input.product_attribute.option_data.pclass_array; variants = input.product_attribute.option_data.variant_array; variants_total = input.product_total_variant; } } callback(variants_total, attribute, variants); }, checkOption: function(variants_total, callback) { var state = true; if (variants_total == 0) { state = false; } callback(state); }, checkTotalStock: function(stateIn, quantity_max, callback) { var state = true; if (stateIn == true && quantity_max > 0) { state = false; } callback(state); }, checkPriceMin: function(variant, callback) { var _self = this; var priceMin = parseFloat(variant[0].price); var comparePriceMin = parseFloat(variant[0].compare_price); for (var i = 0; i < variant.length; i++) { _self.consoleLog('checkPriceMin : priceMin : ', priceMin); _self.consoleLog('checkPriceMin : variant[i].price : ', variant[i].price); if (priceMin >= parseFloat(variant[i].price)) { priceMin = parseFloat(variant[i].price); comparePriceMin = parseFloat(variant[i].compare_price); } } callback(priceMin, comparePriceMin); }, main: function() { var _self = this; $scope.slickCarouselId(); $scope.dataArrayState = _self.stateData(true, false); var dataSend = {}; _self.getApi("shop/current", dataSend, function(res_api) { $scope.shopPointConfig = res_api.data.shop_point_config; _self.getDataProductArray('product/id', function(output) { if (output.data.length != 0) { _self.consoleLog("getDataProductArray : output : ", output.data); _self.quantity(output.data.product_total_stock, function(total_stock) { _self.consoleLog("quantity : total_stock : ", total_stock); $scope.dataProductBuy.quantity_max = total_stock; $scope.dataArray = output.data; if (output.data.product_image.length != 0) { $scope.slickImageGoto(output.data.product_image[0].image_id); } _self.productTab(output.data.product_tags, function(productTab) { $scope.dataArrayTags = productTab; _self.showTab(output.data, function(description, info) { $scope.showTab.dataTab[0].data = description; $scope.showTab.dataTab[1].data = info; }); _self.getAttribute(output.data, function(variants_total, attribute, variants) { _self.consoleLog("getAttribute : variants_total : ", variants_total); _self.consoleLog("getAttribute : attribute : ", attribute); _self.consoleLog("getAttribute : variants : ", variants); _self.checkOption(variants_total, function(state) { _self.checkTotalStock(state, total_stock, function(state) { $scope.buy.state = state; $scope.attribute.attributeOption = attribute; $scope.attribute.dataVariants = variants; $scope.attribute.variantsTotal = variants_total; if (variants_total > 0) { _self.checkPriceMin(variants, function(res_price, res_compare_price) { $scope.dataProductBuy.price = res_price; $scope.dataProductBuy.sumprice = res_price; $scope.dataArray.product_compare_price = res_compare_price; }); } else { $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; } }); }); }); $scope.dataProductBuy.price = output.data.product_price; $scope.dataProductBuy.sumprice = output.data.product_price; _self.getQuantityBreak('product/quantity_break', function(quantity_break) { _self.consoleLog("getQuantityBreak : output : ", quantity_break); $scope.dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.dataProductBuy.result_price = quantity_break[0].unit_price; } }); _self.getNavigationBar(output.data.product_referral_display, 'referral/relation', function(output) { _self.consoleLog("getNavigationBar : output : ", output.data); $scope.navigationBar = output.data; $scope.dataArrayState = _self.stateData(false, true); }); }); }); } else { window.history.back(); } }); }); } } return data; }; $scope.getDataArray().main(); $scope.getShopPointConfigRewardState = function(productPrice) { var state = 'RewardShop'; var sup_price = parseInt(productPrice); if ($scope.shopPointConfig.length != 0) { if (parseInt($scope.shopPointConfig.er_rate) != 0 && parseInt($scope.shopPointConfig.er_earn) != 0) { if (sup_price > 0) { if (parseInt($scope.shopPointConfig.er_rate) <= sup_price) { return 'RewardShop'; } else { return 'High'; } } else { return 'High'; } } else { return 'RewardProduct'; } } else { return 'RewardProduct'; } }; $scope.getShopPointConfigReward = function(productPrice) { var sup_price = 0; var er_rate = 0; var er_earn = 0; var mathFloor = 0; var point = 0; if ($scope.shopPointConfig.length != 0) { sup_price = productPrice; er_rate = parseInt($scope.shopPointConfig.er_rate); er_earn = parseInt($scope.shopPointConfig.er_earn); mathFloor = Math.floor(sup_price / er_rate); point = mathFloor * er_earn; return point; } else { return point; } } $scope.clickckvalue = function() { var result = 0; $scope.promotion_list = $('input[name=radiogroup]:checked').val(); console.log("promotion_list : ", $scope.promotion_list); if ($('input[name=radiogroup]:checked').val() != "" && $('input[name=radiogroup]:checked').val() != undefined) { result = $('input[name=radiogroup]:checked').val(); } else { result = 0; } return result; } }; return promise; });_ui_share_app.directive('productDetailPageV', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageV'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); if (product_tag != '') { var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; } else { $scope.dataRelatetagState = $scope.StateData(false, true); $scope.dataRelatetag = []; return; } console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { // for (var i = 0; i < output.data.dataList.length; i++) { // if(output.data.dataList){ // $scope.dataRelatetag = output.data.dataList; // } // } $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.data_min = []; $scope._dataArrayTags = []; $scope.data_video_id = false; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope.data_video_id = $scope._dataArray.product_id; // if ($scope._dataArray.product_hightlight_video_embed != "") { // $scope._dataArray.product_image.unshift({ // image_url: $scope.imgPath + 'img-play.png', // product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed // }); // } $scope._dataArrayRelateProductId = res.data.product_id; if (res.data.product_tags != "") { $scope._dataArrayTags = res.data.product_tags.split(","); } if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.productRelateTag($scope._dataArray.product_tags, $scope._dataArray.product_referral_display.category[0].referral_id); if (res.data.product_attribute.option_data != 0 && res.data.product_total_variant > 0) { if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { // alert("x๊อบไข่สด"); var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ", $scope.data_min); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); $scope.buildVariantOption(res.data); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 98) { i = 98; } if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } if (i > 98) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 99; e.val(99); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; // $scope.onClickVariantItems(); }; $scope.dataVariantsPick = []; $scope.buy_button = false; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; $scope.buy_button = false; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.buy_button = true; $scope.findVariantsData($scope.dataVariantsPick); } }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; //window.location.href='login'; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); /* $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); */ } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('productDetailPageVa', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageVa'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d ,$scope).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); if (product_tag != '') { var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; } else { $scope.dataRelatetagState = $scope.StateData(false, true); $scope.dataRelatetag = []; return; } console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend ,$scope).then(function(output) { if (output.ok == 1) { // for (var i = 0; i < output.data.dataList.length; i++) { // if(output.data.dataList){ // $scope.dataRelatetag = output.data.dataList; // } // } $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope.data_relate_pro = []; $scope._getDataRelate = function(id, limit) { var dataSend = { 'txt_product_id': id, 'txt_limit': limit, }; GAEAPI.get('product/related', dataSend, $scope).then(function(output) { if (output.ok == 1) { // $scope.$apply(function() { $scope.data_relate_pro = output.data.lists; // }); } }); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.data_min = []; $scope._dataArrayTags = []; $scope.data_video_id = false; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend ,$scope).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope.data_video_id = $scope._dataArray.product_id; // if ($scope._dataArray.product_hightlight_video_embed != "") { // $scope._dataArray.product_image.unshift({ // image_url: $scope.imgPath + 'img-play.png', // product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed // }); // } $scope._dataArrayRelateProductId = res.data.product_id; if (res.data.product_tags != "") { $scope._dataArrayTags = res.data.product_tags.split(","); } if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.productRelateTag($scope._dataArray.product_tags, $scope._dataArray.product_referral_display.category[0].referral_id); $scope._getDataRelate($scope.data_video_id,8); // if (res.data.product_attribute.option_data != 0 && res.data.product_total_variant > 0) { // if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { // // alert("x๊อบไข่สด"); // var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; // for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { // if (parseInt(set_varia0) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { // set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; // $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; // } // } // if ($scope.data_min.length == 0) { // $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; // } // console.log("iujdishjdskd : ", $scope.data_min); // $scope.buildVariantOption(res.data); // } // $scope._dataArray.product_price = $scope.data_min.price; // $scope._dataArray.product_compare_price = $scope.data_min.compare_price; // } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 98) { i = 98; } if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } if (i > 98) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 99; e.val(99); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; // $scope.onClickVariantItems(); }; $scope.dataVariantsPick = []; $scope.buy_button = false; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; $scope.buy_button = false; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.buy_button = true; $scope.findVariantsData($scope.dataVariantsPick); } }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; //window.location.href='login'; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); /* $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); */ } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('productDetailPageVb', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageVb'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', imgcart: '@imgcart', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); if (product_tag != '') { var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; } else { $scope.dataRelatetagState = $scope.StateData(false, true); $scope.dataRelatetag = []; return; } console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { // for (var i = 0; i < output.data.dataList.length; i++) { // if(output.data.dataList){ // $scope.dataRelatetag = output.data.dataList; // } // } $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope.qtyProduct = 1; $scope.result_price = 0; $scope.checkQty = function(qtyProduct) { var productQuantityBreak = GAEAPI.getValueForKey($scope._data_product_id, "product_quantity_break", []); var quantityBreak = GAEAPI.getValueForKey(productQuantityBreak, "quantity_break", []); var product_price = GAEAPI.getValueForKey($scope._data_product_id, "product_price", 0); console.log("quantityBreak : ", quantityBreak); console.log("quantityBreak : qtyProduct : ", qtyProduct); for (var index in quantityBreak) { var rowData = quantityBreak[index]; var amount_end = parseInt(GAEAPI.getValueForKey(rowData, "amount_end", 0)); var unit_price = parseInt(GAEAPI.getValueForKey(rowData, "unit_price", 0)); if (qtyProduct >= amount_end) { $scope.result_price = unit_price; } } }; $scope.getQuantityBreak = function(dataSend, api, callback) { console.log("getQuantityBreak : dataSend : ", dataSend, " api : ", api); var quantity_break = []; GAEAPI.get(api, dataSend).then(function(output) { console.log("getQuantityBreak : output : ", output); if (output.ok == 1) { quantity_break = output.data.quantity_break; callback(quantity_break); } callback(quantity_break); }); callback(quantity_break); }; $scope.checkLogin = function(urlApi, product_id, status_login, callback) { var dataSend = {}; var productId = parseInt(product_id); var statusLogin = status_login; var api = urlApi; var customerId = 0; if (api == 'product/id') { dataSend = { 'txt_product_id': productId, } console.log("checkLogin : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); callback(statusLogin, customerId, dataSend, api); } else if (api == 'product/quantity_break') { if (statusLogin) { customerId = parseInt(UiCustomerBox.delegate.get.me().customer_id); dataSend = { 'txt_product_id': productId, 'txt_customer_id': customerId, } console.log("checkLogin : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); callback(statusLogin, customerId, dataSend, api); } else { console.log("checkLogin : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); callback(statusLogin, customerId, dataSend, api); } } }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.data_min = []; $scope._dataArrayTags = []; $scope.data_video_id = false; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope.data_video_id = $scope._dataArray.product_id; // if ($scope._dataArray.product_hightlight_video_embed != "") { // $scope._dataArray.product_image.unshift({ // image_url: $scope.imgPath + 'img-play.png', // product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed // }); // } $scope._dataArrayRelateProductId = res.data.product_id; if (res.data.product_tags != "") { $scope._dataArrayTags = res.data.product_tags.split(","); } if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.checkLogin('product/quantity_break', dataSend.txt_product_id, UiCustomerBox.delegate.get.isLogin() , function(statusLogin, customerId, dataSend, api) { console.log("getProductId checkLogin callback : statusLogin : ", statusLogin, " customerId : ", customerId, " dataSend : ", dataSend, " api : ", api); if (statusLogin) { console.log("getProductId checkLogin : IF"); $scope.getQuantityBreak(dataSend, api, function(quantity_break) { console.log("getProductId checkLogin callback getQuantityBreak : quantity_break : ", quantity_break); $scope._dataArray.product_quantity_break.quantity_break = quantity_break; if (quantity_break.length) { $scope.result_price = quantity_break[0].unit_price; } }); } else { console.log("getProductId checkLogin : ELSE") } }); $scope.productRelateTag($scope._dataArray.product_tags, $scope._dataArray.product_referral_display.category[0].referral_id); if (res.data.product_attribute.option_data != 0 && res.data.product_total_variant > 0) { if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { // alert("x๊อบไข่สด"); var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ", $scope.data_min); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); $scope.buildVariantOption(res.data); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 98) { i = 98; } if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } if (i > 98) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 99; e.val(99); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; // $scope.onClickVariantItems(); }; $scope.dataVariantsPick = []; $scope.buy_button = false; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; $scope.buy_button = false; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.buy_button = true; $scope.findVariantsData($scope.dataVariantsPick); } }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; //window.location.href='login'; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); /* $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); */ } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.Relate_dataArray = []; $scope._getRelateDataArray = function(id) { var dataSend = { 'txt_product_id': id, 'txt_limit': 10, }; // $scope.consoleLog('_getDataArray dataSend', dataSend); GAEAPI.get('product/related', dataSend, $scope).then(function(output) { // $scope.consoleLog('_getDataArray output', output); if (output.ok == 1) { // $scope.$apply(function() { $scope.Relate_dataArray = output.data.lists; // $scope.consoleLog('_getDataArray _dataArray', $scope._dataArray); console.log("slofkdsfdfds;lfsdk;f : ", $scope.Relate_dataArray); // }); } // $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope._getRelateDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope.buildTitleUrl = function (str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productDetailPageVc', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageVc'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); if (product_tag != '') { var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; } else { $scope.dataRelatetagState = $scope.StateData(false, true); $scope.dataRelatetag = []; return; } console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { // for (var i = 0; i < output.data.dataList.length; i++) { // if(output.data.dataList){ // $scope.dataRelatetag = output.data.dataList; // } // } $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.getNameBadgeId = function(id) { if (id == '72') { return 'New Arrival' } else if (id == '74') { return 'Recommend' } else if (id == '75') { return 'Best Seller' } else { return 'null'; } }; $scope.data_min = []; $scope._dataArrayTags = []; $scope.data_video_id = false; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; console.log("product/id : dataSend : ", dataSend); GAEAPI.get('product/id', dataSend).then(function(res) { console.log("product/id : output : ", res); if (res.ok === 1) { $scope._dataArray = res.data; $scope.data_video_id = $scope._dataArray.product_id; // if ($scope._dataArray.product_hightlight_video_embed != "") { // $scope._dataArray.product_image.unshift({ // image_url: $scope.imgPath + 'img-play.png', // product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed // }); // } $scope._dataArrayRelateProductId = res.data.product_id; if (res.data.product_tags != "") { $scope._dataArrayTags = res.data.product_tags.split(","); } if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.productRelateTag($scope._dataArray.product_tags, $scope._dataArray.product_referral_display.category[0].referral_id); if (res.data.product_attribute.option_data != 0 && res.data.product_total_variant > 0) { if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { // alert("x๊อบไข่สด"); var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ", $scope.data_min); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); $scope.buildVariantOption(res.data); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 98) { i = 98; } if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } if (i > 98) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 99; e.val(99); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; // $scope.onClickVariantItems(); }; $scope.dataVariantsPick = []; $scope.buy_button = false; $scope.showComment = false; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; $scope.buy_button = false; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.buy_button = true; $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.getShowComment = function(show) { $scope.showComment = true; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; //window.location.href='login'; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); /* $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); */ } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.clickckvalue = function() { var result = 0; $scope.promotion_list = $('input[name=radiogroup]:checked').val(); console.log("promotion_list : ", $scope.promotion_list); if ($('input[name=radiogroup]:checked').val() != "" && $('input[name=radiogroup]:checked').val() != undefined) { result = $('input[name=radiogroup]:checked').val(); } else { result = 0; } return result; } }; return promise; });_ui_share_app.directive('productDetailPageVca', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageVca'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { promotelink: '@promotelink', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); if (product_tag != '') { var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; } else { $scope.dataRelatetagState = $scope.StateData(false, true); $scope.dataRelatetag = []; return; } console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { // for (var i = 0; i < output.data.dataList.length; i++) { // if(output.data.dataList){ // $scope.dataRelatetag = output.data.dataList; // } // } $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.getNameBadgeId = function(id) { if (id == '72') { return 'New Arrival' } else if (id == '74') { return 'Recommend' } else if (id == '75') { return 'Best Seller' } else { return 'null'; } }; $scope.data_min = []; $scope._dataArrayTags = []; $scope.data_video_id = false; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; console.log("product/id : dataSend : ", dataSend); GAEAPI.get('product/id', dataSend).then(function(res) { console.log("product/id : output : ", res); if (res.ok === 1) { $scope._dataArray = res.data; $scope.data_video_id = $scope._dataArray.product_id; // if ($scope._dataArray.product_hightlight_video_embed != "") { // $scope._dataArray.product_image.unshift({ // image_url: $scope.imgPath + 'img-play.png', // product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed // }); // } $scope._dataArrayRelateProductId = res.data.product_id; if (res.data.product_tags != "") { $scope._dataArrayTags = res.data.product_tags.split(","); } if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.productRelateTag($scope._dataArray.product_tags, $scope._dataArray.product_referral_display.category[0].referral_id); if (res.data.product_attribute.option_data != 0 && res.data.product_total_variant > 0) { if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { // alert("x๊อบไข่สด"); var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ", $scope.data_min); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); $scope.buildVariantOption(res.data); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 98) { i = 98; } if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } if (i > 98) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 99; e.val(99); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; // $scope.onClickVariantItems(); }; $scope.dataVariantsPick = []; $scope.buy_button = false; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; $scope.buy_button = false; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.buy_button = true; $scope.findVariantsData($scope.dataVariantsPick); } }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; //window.location.href='login'; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); /* $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); */ } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.clickckvalue = function() { var result = 0; $scope.promotion_list = $('input[name=radiogroup]:checked').val(); console.log("promotion_list : ", $scope.promotion_list); if ($('input[name=radiogroup]:checked').val() != "" && $('input[name=radiogroup]:checked').val() != undefined) { result = $('input[name=radiogroup]:checked').val(); } else { result = 0; } return result; } }; return promise; });_ui_share_app.directive('productDetailPageVx', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageVx'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.backgroundImageId = ''; $scope.toBackgroundImageId = function(id) { console.log('toBackgroundImageId : id : ', id); $scope.backgroundImageId = id; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); if (product_tag != '') { var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; } else { $scope.dataRelatetagState = $scope.StateData(false, true); $scope.dataRelatetag = []; return; } console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { // for (var i = 0; i < output.data.dataList.length; i++) { // if(output.data.dataList){ // $scope.dataRelatetag = output.data.dataList; // } // } $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.data_min = []; $scope._dataArrayTags = []; $scope.data_video_id = false; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope.data_video_id = $scope._dataArray.product_id; // if ($scope._dataArray.product_hightlight_video_embed != "") { // $scope._dataArray.product_image.unshift({ // image_url: $scope.imgPath + 'img-play.png', // product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed // }); // } $scope._dataArrayRelateProductId = res.data.product_id; if (res.data.product_tags != "") { $scope._dataArrayTags = res.data.product_tags.split(","); } if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.productRelateTag($scope._dataArray.product_tags, $scope._dataArray.product_referral_display.category[0].referral_id); if (res.data.product_attribute.option_data != 0 && res.data.product_total_variant > 0) { if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { console.log("res.data.product_attribute.option_data.variant_array : ", res.data.product_attribute.option_data.variant_array); var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseFloat(set_varia0) >= parseFloat(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } if ($scope.data_min.length != 0) { if ($scope.data_min.variant_image.length != 0) { $scope.toBackgroundImageId($scope.data_min.variant_image[0].image_id); } } console.log("iujdishjdskd : ", $scope.data_min); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); $scope.buildVariantOption(res.data); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseFloat(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseFloat(e.val()); if (i > 19) { i = 19; } if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseFloat(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } if (i > 19) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 20; e.val(20); }, 600); } }; $scope.slickGoto = function(idx) { console.log('slickGoto : idx : ', idx); setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; // $scope.onClickVariantItems(); }; $scope.dataVariantsPick = []; $scope.buy_button = false; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; $scope.buy_button = false; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.buy_button = true; $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.checkPrice = function(price) { var check_price = 0; var _price = (price != undefined && price != "" && price != null) ? price.toString() : "0"; if (_price.includes(".")) { check_price = 2; } return check_price; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; console.log("findVariantsData : dataVariants : ", dataVariants); for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; // if (dataVariants[i].variant_image.length != 0) { // $scope._dataArray.product_image = dataVariants[i].variant_image; // $scope.mkCarousel(); // } if (dataVariants[i].variant_image.length != 0) { $scope.toBackgroundImageId(dataVariants[i].variant_image[0].image_id); } $scope.max_length = dataVariants[i].total_stock; break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.mkCarousel = function() { var key = $('[data-key="' + $scope._key() + '"]'); var gall = $('[data-gall="' + $scope._key() + '"]'); key.css('height', '0'); key.css('opacity', '0'); gall.css('height', '0'); gall.css('opacity', '0'); setTimeout(function() { key.css('height', 'auto'); key.css('opacity', '1'); gall.css('height', 'auto'); gall.css('opacity', '1'); }, 1500); }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; //window.location.href='login'; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); /* $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); */ } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('productDetailPageW', function($rootScope, $routeParams, sliderProvider, $componentProductDetail, $location) { var templateName = 'productDetailPageW'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', imgcart: '@imgcart', view: '@viewcart', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; if ($scope.imgcart != undefined) { $scope.setimg_cart = $scope.icnPath + $scope.imgcart; } $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope.names = 20; $scope._dataArray_tag = []; $scope._dataArray = []; $scope.data_video_id = false; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope.data_video_id = $scope._dataArray.product_id; /*if ($scope._dataArray.product_hightlight_video_embed != "") { $scope._dataArray.product_image.unshift({ image_url: $scope.imgPath + 'img-play.png', product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed }); }*/ $scope._dataArray_tag = res.data.product_tags.split(","); $scope._dataArrayRelateProductId = res.data.product_id; if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.productRelateTag($scope._dataArray.product_tags); $scope.buildVariantOption(res.data); if (res.data.product_attribute.length != 0) { $scope.buildMultipleQuantity(res.data); } if (res.data.product_total_variant == 0 && res.data.product_total_stock > 0) { $scope.names = parseInt(res.data.product_total_stock); console.log("nnames stock :", $scope.names); } if (res.data.product_total_variant == 0 && res.data.product_total_stock < 0) { $scope.names = 20; console.log("nnames stock :", $scope.names); } if (res.data.product_total_variant > 0) { $scope.names = 20; } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '#gallery_slider[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope._data_qty_selected = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (isNaN(i)) { i = 0; } if (i < $scope.names) { e.val(i + 1); $scope._data_qty_selected = (i + 1); } return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.onSelectVariantItems(0, ''); }; $scope.dataVariantsPick = []; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $timeout.cancel(s); $('select.variantSelector').each(function(idx, obj) { var optionElementFirst = $(this).find('option[data-index="' + idx + '"]').eq(0); optionElementFirst.prop("selected", true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var _self = dataVariants[i]; var _self_option = angular.fromJson(_self.option_id_json); console.log("selectedOptionTextJson: option", dataVariants); var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; if (dataVariants[i].total_stock != 0) { $scope.names = dataVariants[i].total_stock; } else { $scope.names = 20; } $scope.switchQuantityByKey('-' + variantsPick.join('-') + '-'); console.log("selectedOptionTextJson: option", _self); if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope._dataArray.product_image.length; im++) { if ($scope._dataArray.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } $timeout(function() { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { $scope._slickGoto('gallery_show', rightImagePosition); } else { angular.element('.gallery-thumbnail .thumb-img[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300); } break; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.currentOptionQtyPick = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } return e.val(); }; $scope.switchQuantityByKey = function(variant_key) { $scope.lastCheckedVariantKey = variant_key; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price[variant-key!="' + variant_key + '"]').removeClass('active').removeClass('inin'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('active'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('active'); $timeout(function() { $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('inin'); }, 300); }; $scope.productQuantityMultiArray = []; $scope.lastCheckedVariantKey = ''; $scope.buildMultipleQuantity = function(productObj) { $scope.productQuantityMultiArray = []; var r = [], p = productObj.product_attribute.option_data.variant_array; for (var i = 0; i < p.length; i++) { if (p[i].status == 1 && p[i].status == 1) { $scope.productQuantityMultiArray.push({ v_key: p[i].variant_key, v_name: p[i].option_name_array[0], v_qty: 1, v_active: 0 }); } } }; $scope.dataVariantsPick = []; $scope.electric = []; $scope.testyuyu = 0; $scope.onSelectVariantItems = function($index, option_id) { $scope.testyuyu = 0; if (option_id == '') { $scope.testyuyu = 0; $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_not_result').addClass("active"); $scope.dataVariantsPick[$index] = option_id; console.log("check_vareian 1000:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length); return GAEAPI.get('product/id', { 'txt_product_id': $scope._idUrl($scope._viewRouteParams().product_id) }).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; for (var i = 0; i < $scope.dataVariantsPick.length; i++) { if ($scope.dataVariantsPick[i] != undefined && $scope.dataVariantsPick[i] != "") { $scope.testyuyu++; } } if ($scope.testyuyu >= $scope.dataOption.length) { $scope.testyuyu = 0; $('.d_qty_not_result').removeClass("active"); $scope.findVariantsData($scope.dataVariantsPick); } else { $scope.testyuyu = 0; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); } console.log("check_vareian 1001:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length, $scope.electric); } }; $scope.ifOptionUnSelect = function() { return ($('.d_qty_price.active.inin').length > 0) ? true : false; }; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('productDetailPageWa', function($rootScope, $routeParams, sliderProvider, $componentProductDetail, $location) { var templateName = 'productDetailPageWa'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', imgcart: '@imgcart', view: '@viewcart', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; if ($scope.imgcart != undefined) { $scope.setimg_cart = $scope.icnPath + $scope.imgcart; } $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; /*if ($scope._dataArray.product_hightlight_video_embed != "") { $scope._dataArray.product_image.unshift({ image_url: $scope.imgPath + 'img-play.png', product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed }); }*/ $scope._dataArrayRelateProductId = res.data.product_id; if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } if(res.data.product_attribute.option_data != 0 && res.data.product_total_variant > 0){ if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { } } $scope.productRelateTag($scope._dataArray.product_tags); $scope.buildVariantOption(res.data); if (res.data.product_attribute.length != 0) { $scope.buildMultipleQuantity(res.data); } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '#gallery_slider[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope._data_qty_selected = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.onSelectVariantItems(0, ''); }; $scope.dataVariantsPick = []; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $timeout.cancel(s); $('select.variantSelector').each(function(idx, obj) { var optionElementFirst = $(this).find('option[data-index="' + idx + '"]').eq(0); optionElementFirst.prop("selected", true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var _self = dataVariants[i]; var _self_option = angular.fromJson(_self.option_id_json); var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope.switchQuantityByKey('-' + variantsPick.join('-') + '-'); console.log("selectedOptionTextJson: option", _self); if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope._dataArray.product_image.length; im++) { if ($scope._dataArray.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } $timeout(function() { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { $scope._slickGoto('gallery_show', rightImagePosition); } else { angular.element('.gallery-thumbnail .thumb-img[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300); } break; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.currentOptionQtyPick = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } return e.val(); }; $scope.switchQuantityByKey = function(variant_key) { $scope.lastCheckedVariantKey = variant_key; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price[variant-key!="' + variant_key + '"]').removeClass('active').removeClass('inin'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('active'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('active'); $timeout(function() { $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('inin'); }, 300); }; $scope.productQuantityMultiArray = []; $scope.lastCheckedVariantKey = ''; $scope.buildMultipleQuantity = function(productObj) { $scope.productQuantityMultiArray = []; var r = [], p = productObj.product_attribute.option_data.variant_array; for (var i = 0; i < p.length; i++) { if (p[i].status == 1 && p[i].status == 1) { $scope.productQuantityMultiArray.push({ v_key: p[i].variant_key, v_name: p[i].option_name_array[0], v_qty: 1, v_active: 0 }); } } }; $scope.dataVariantsPick = []; $scope.electric = []; $scope.testyuyu = 0; $scope.onSelectVariantItems = function($index, option_id) { $scope.testyuyu = 0; if (option_id == '') { $scope.testyuyu = 0; $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_not_result').addClass("active"); $scope.dataVariantsPick[$index] = option_id; console.log("check_vareian 1000:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length); return GAEAPI.get('product/id', { 'txt_product_id': $scope._idUrl($scope._viewRouteParams().product_id) }).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; for (var i = 0; i < $scope.dataVariantsPick.length; i++) { if ($scope.dataVariantsPick[i] != undefined && $scope.dataVariantsPick[i] != "") { $scope.testyuyu++; } } if ($scope.testyuyu >= $scope.dataOption.length) { $scope.testyuyu = 0; $('.d_qty_not_result').removeClass("active"); $scope.findVariantsData($scope.dataVariantsPick); } else { $scope.testyuyu = 0; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); } console.log("check_vareian 1001:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length, $scope.electric); } }; $scope.ifOptionUnSelect = function() { return ($('.d_qty_price.active.inin').length > 0) ? true : false; }; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('productDetailPageWorldcamera', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageWorldcamera'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', type: '@type', cart: '@cart', buycol: '@buycol', buyicon: '@buyicon', buytext: '@buytext', viewcarttext: '@viewcarttext', buylogin: '@buylogin', currency: '@currency', checkstaff: '@checkstaff', language: '@language', btnstyle: '@btnstyle', maxstock: '@maxstock', videotext: '@videotext', description: '@description', info: '@info', specification: '@specification', textbrand:'@textbrand', navigationhover: '@navigationhover', imageappcoverchecked: '@imageappcoverchecked', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http, $location ,share) { $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._component = "productDetailPageWorldcamera"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._type = $scope._componentType + $scope._class + ".html"; $scope._cart = ($scope.cart != undefined && $scope.cart != "") ? $scope.cart : "trumpComponentCarts"; $scope._buycol = ($scope.buycol != undefined && $scope.buycol != "") ? parseInt($scope.buycol) : 15; $scope._maxstock = ($scope.maxstock != undefined && $scope.maxstock != "") ? parseInt($scope.maxstock) : 20; $scope._btnstyle = ($scope.btnstyle != undefined && $scope.btnstyle != "") ? $scope.btnstyle : "filled_button_large"; $scope._buylogin = ($scope.buylogin == "true" || $scope.buylogin == "t") ? true : false; $scope._checkstaff = ($scope.checkstaff == "true" || $scope.checkstaff == "t") ? true : false; $scope._currency = ($scope.currency != undefined && $scope.currency != "") ? $scope.currency : "THB"; $scope._buyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope.buyicon : "icnt_outline_cart01_dark.png"; $scope._buytext = ($scope.buytext != undefined && $scope.buytext != "") ? $scope.buytext : "เพิ่มในรถเข็น"; $scope._viewcarttext = ($scope.viewcarttext != undefined && $scope.viewcarttext != "") ? $scope.viewcarttext : "ดูรถเข็น"; $scope._videotext = ($scope.videotext != undefined && $scope.videotext != "") ? $scope.videotext : "Video"; $scope._icebuyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope._icnPath + $scope.buyicon : $scope._icnPath + "icnt_outline_cart01_dark.png"; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; $scope._textbrand = ($scope.textbrand != undefined && $scope.textbrand != "") ? $scope.textbrand : "Brand"; $scope._navigationhover = ($scope.navigationhover != undefined && $scope.navigationhover != "") ? $scope.navigationhover : "primary"; $scope._imageappcoverchecked = ($scope.imageappcoverchecked == "true" || $scope.imageappcoverchecked == "t") ? true : false; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getNamePage: function(arr) { var str = []; for (var i = 0; i < arr.length; i++) { if (i != 0) { str.push(arr[i]); } } return str.join(" "); }, getProductId: function(params, callback) { var _self = this; var product_id = (params.product_id != undefined) ? params.product_id.split("-", 1).join("") : false; _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getReferralId: function(productReferralDisplay, callback) { var _self = this; var referral_id = 0; if (productReferralDisplay.length != 0) { if (productReferralDisplay.category != undefined) { if (productReferralDisplay.category.length != 0) { referral_id = productReferralDisplay.category[0].referral_id } } } callback(referral_id); }, getStaffId: function(staffId, callback) { var _self = this; var res_staff = { staff_id: (staffId != 0 && staffId != '' && staffId != undefined) ? staffId : '0', status: (staffId != 0 && staffId != '' && staffId != undefined) ? true : false } callback(res_staff); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carouselA: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ fade: true, dots: false, arrows: false, infinite: true, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselB: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: true, arrows: true, infinite: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselD: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: false, arrows: true, infinite: true, autoplay: true, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselBar: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: false, arrows: false, infinite: false, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 6, slidesToScroll: 6, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 5, slidesToScroll: 5, } }, { breakpoint: 991, settings: { slidesToShow: 4, slidesToScroll: 4, } }, { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 3, } }] }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, slickCarousel: function(carousel, index) { var _self = this; $scope.setCarousel.index = index; setTimeout(function() { $('[data-key="' + carousel + '"]').slick('slickGoTo', index); }, 100); }, prevIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != 0) ? image_index - 1 : image - 1; _self.consoleLog("prevIndex index", $scope.setCarousel.index); }, nextIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != (image - 1)) ? image_index + 1 : 0; _self.consoleLog("nextIndex index", $scope.setCarousel.index); } } return getFunction; }; $scope.getAttribute = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, productAttribute: function(productAttribute, callback) { var _self = this; var attribute = { option_name: "", option_attribute: [] }; if (productAttribute.option_data != undefined) { if (productAttribute.option_data.variant_array != undefined && productAttribute.option_data.variant_array.length != 0) { for (var a = 0; a < productAttribute.option_data.pclass_array.length; a++) { attribute.option_name = attribute.option_name.concat(productAttribute.option_data.pclass_array[a].pclass_name, " "); } for (var b = 0; b < productAttribute.option_data.variant_array.length; b++) { var product_attribute = { product_id: productAttribute.option_data.variant_array[b].product_id, product_sku: productAttribute.option_data.variant_array[b].sku, product_title: "", product_price: parseFloat(productAttribute.option_data.variant_array[b].price), product_compare_price: parseFloat(productAttribute.option_data.variant_array[b].compare_price), product_total_stock: parseFloat(productAttribute.option_data.variant_array[b].total_stock), product_image: productAttribute.option_data.variant_array[b].variant_image } for (var c = 0; c < productAttribute.option_data.variant_array[b].option_name_array.length; c++) { product_attribute.product_title = product_attribute.product_title.concat(productAttribute.option_data.variant_array[b].option_name_array[c], " "); } attribute.option_attribute.push(product_attribute); } } } _self.consoleLog("productAttribute attribute ", attribute); callback(attribute); }, checkDiscountPrice: function(productDiscount, resPrice, resComparePrice, callback) { var _self = this; var price = 0; var compare_price = 0; if (productDiscount.length == 0) { price = parseFloat(resPrice); compare_price = parseFloat(resComparePrice); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(resPrice) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(resPrice); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(resPrice) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(resPrice); } } callback(price, compare_price); }, checkMinPrice: function(option, callback) { var _self = this; var price_min = parseFloat(option.option_attribute[0].product_price); var compare_price_min = parseFloat(option.option_attribute[0].product_compare_price); var total_stock = parseFloat(option.option_attribute[0].product_total_stock); for (var a = 0; a < option.option_attribute.length; a++) { if (price_min >= parseFloat(option.option_attribute[a].product_price)) { price_min = parseFloat(option.option_attribute[a].product_price); compare_price_min = parseFloat(option.option_attribute[a].product_compare_price); total_stock = parseFloat(option.option_attribute[a].product_total_stock); } } _self.consoleLog("checkPriceMin price_min ", price_min); _self.consoleLog("checkPriceMin compare_price_min ", compare_price_min); _self.consoleLog("checkPriceMin total_stock ", total_stock); callback(price_min, compare_price_min, total_stock); }, getTotalStock: function(totalStock, mixStock, callback) { var _self = this; var total_stock = (totalStock > 0) ? ((totalStock <= mixStock) ? totalStock : mixStock) : ((totalStock == -1) ? mixStock : totalStock); callback(total_stock); }, checkMinPrices: function(api, attribute, callback) { var _self = this; var dataPrice = { product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 } } if (attribute.option_attribute.length == 0) { _self.checkDiscountPrice(api.data.product_discount, api.data.product_price, api.data.product_compare_price, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(api.data.product_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, false); }); }); }); }); }); } else { _self.checkMinPrice(attribute, function(res_price_min, res_compare_price_min, res_total_stock) { _self.checkDiscountPrice(api.data.product_discount, res_price_min, res_compare_price_min, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(res_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, true); }); }); }); }); }); }); } }, priceIncludes: function(price, includes, callback) { var _self = this; var priceToString = (price == null) ? 0 : price; _self.consoleLog('priceIncludes priceToString : ', priceToString); callback(priceToString.toString().includes(includes)); }, checkPrice: function(price, callback) { var _self = this; _self.priceIncludes(price, '.', function(res) { _self.consoleLog("checkPrice res ", res); callback((!res) ? 0 : 2); }); }, onSelectOption: function(productId) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = productId; _self.consoleLog("onSelectOption productId ", productId); $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); for (var a = 0; a < $scope.data.attribute.dataArray.option_attribute.length; a++) { _self.consoleLog("onSelectOption option_attribute ", $scope.data.attribute.dataArray.option_attribute[a]); if ($scope.data.attribute.dataArray.option_attribute[a].product_id == productId) { if ($scope.data.attribute.dataArray.option_attribute[a].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var b = 0; b < $scope.dataApi.product.dataArray.product_image.length; b++) { if ($scope.dataApi.product.dataArray.product_image[b].image_id == $scope.data.attribute.dataArray.option_attribute[a].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, b); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[a].product_price, $scope.data.attribute.dataArray.option_attribute[a].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[a].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); break; } } }, onClickOption: function(index) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.data.attribute.productId = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); if ($scope.data.attribute.dataArray.option_attribute[index].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataApi.product.dataArray.product_image.length; i++) { if ($scope.dataApi.product.dataArray.product_image[i].image_id == $scope.data.attribute.dataArray.option_attribute[index].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, i); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[index].product_price, $scope.data.attribute.dataArray.option_attribute[index].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[index].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); } } return getFunction; }; $scope.getAttributeCustom = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, createArray: function(productCustomTemplates, callback) { var _self = this; var custom_attributes = []; if (productCustomTemplates.templates.length != 0) { angular.forEach(productCustomTemplates.templates, function(item, index) { if (item.option_sets.length != 0) { _self.getAttributes(item.option_sets, function(res_attributes) { custom_attributes = custom_attributes.concat(res_attributes); }); } }); /* if (productCustomTemplates.templates[0].option_sets.length != 0) { _self.getAttributes(productCustomTemplates.templates[0].option_sets, function(res_attributes) { custom_attributes = res_attributes; }); } */ } _self.consoleLog("createArray : productCustomTemplates", productCustomTemplates); _self.consoleLog("createArray : custom_attributes", custom_attributes); callback(custom_attributes, true); }, formatAttribute: function(index, optionSubsetIndex, setType, optionSetArray, callback) { var _self = this; var set_id = (setType == 'attribute') ? optionSetArray.set_id : optionSetArray.subset_id; var attribute = { attribute_index: index, attribute_option_subset_index: optionSubsetIndex, active_option_id: (optionSetArray.option_data.select_id != 0) ? optionSetArray.option_data.select_id : "-1", active_option_index: -1, active_option_index_str: "-1", active_textarea: "", active_array: [], set_id: set_id, name: optionSetArray.name, set_type: optionSetArray.ss_type, option: [] } callback(attribute); }, getOption: function(index, optionDataArray, callback) { var _self = this; var options = { index: index, ss_data_id: optionDataArray.ss_data_id, name: optionDataArray.name, image: optionDataArray.image, price: optionDataArray.price, compare_price: 0, total_stock: 0 } callback(options); }, getActive: function(index, activeOptionId, activeOptionIdIn, optionDataArray, callback) { var _self = this; var actives_index = (optionDataArray.ss_data_id == activeOptionId) ? index : activeOptionIdIn; var actives = (optionDataArray.ss_data_id != activeOptionId) ? "0" : "1"; callback(actives_index, actives); }, getAttributes: function(optionSetArray, callback) { var _self = this; var attributes = []; for (var index = 0; index < optionSetArray.length; index++) { _self.formatAttribute(index, 0, 'attribute', optionSetArray[index], function(res_attribute) { if (optionSetArray[index].option_subsets.length != 0) { for (var option_subset_index = 0; option_subset_index < optionSetArray[index].option_subsets.length; option_subset_index++) { _self.formatAttribute(index, option_subset_index, res_attribute.set_type, optionSetArray[index].option_subsets[option_subset_index], function(res_attribute_sub) { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_subsets[option_subset_index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute_sub.active_option_id, active_option_id, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute_sub.option = options; res_attribute_sub.active_option_index = active_option_id; res_attribute_sub.active_option_index_str = String(active_option_id); res_attribute_sub.active_array = active_option_array; attributes.push(res_attribute_sub); }); } } else { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute.active_option_id, active_option_id, optionSetArray[index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute.option = options; res_attribute.active_option_index = active_option_id; res_attribute.active_option_index_str = String(active_option_id); res_attribute.active_array = active_option_array; attributes.push(res_attribute); } }); } callback(attributes) }, getformatQuantity: function(index, attributeCustom, callback) { var _self = this; var quantity = { name: String(index + 1), dataArray: attributeCustom } callback(quantity); }, onClickRadio: function(index, index_option) { var _self = this; _self.consoleLog("onClickRadio : index", index); _self.consoleLog("onClickRadio : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickRadio : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickDropdown: function(index, index_option) { var _self = this; _self.consoleLog("onClickDropdown : index", index); _self.consoleLog("onClickDropdown : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickDropdown : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickCheckbox: function(index, index_option) { var _self = this; _self.consoleLog("onClickCheckbox : index", index); _self.consoleLog("onClickCheckbox : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i == parseInt(index_option)) ? (($scope.data.attribute_custom.dataArray[index].active_array[i] != "0") ? "0" : "1") : $scope.data.attribute_custom.dataArray[index].active_array[i]; } _self.consoleLog("onClickCheckbox : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); } } return getFunction; }; $scope.getReward = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, momentUnix: function(callback) { var _self = this; var now = moment().unix(); callback(now); }, getCalculator: function(sumProductPrice, reward, callback) { var _self = this; _self.consoleLog("getCalculator : sumProductPrice", sumProductPrice); _self.consoleLog("getCalculator : reward", reward); var point_reward = 0; if (reward.type_id == "100") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } else if (reward.type_id == "101") { point_reward = reward.reward_amount; } else if (reward.type_id == "102") { point_reward = (reward.reward_percent * sumProductPrice.price) / 100; } else if (reward.type_id == "103") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } _self.consoleLog("getCalculator : point_reward", point_reward); callback(point_reward); }, getProductReward: function(now, productReward, callback) { var _self = this; var reward = { reward_length: (productReward.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(productReward.reward_lifetime.lifetime_start_time); reward.lifetime_end_time = parseInt(productReward.reward_lifetime.lifetime_end_time); reward.type_id = productReward.reward_type_id; reward.amount = parseInt(productReward.reward_amount); reward.percent = parseInt(productReward.reward_percent); reward.every_price = parseInt(productReward.reward_every_price); } _self.consoleLog("getProductReward : reward", reward); callback(reward); }, getPointConfig: function(now, shopPointConfig, callback) { var _self = this; var reward = { reward_length: (shopPointConfig.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(shopPointConfig.er_from); reward.lifetime_end_time = parseInt(shopPointConfig.er_to); reward.type_id = "100"; reward.amount = parseInt(shopPointConfig.er_earn); reward.every_price = parseInt(shopPointConfig.er_rate); } _self.consoleLog("getPointConfig : reward", reward); callback(reward); }, checkPointReward: function(reward, callback) { var _self = this; var state = false; if (reward.reward_length) { var start = reward.lifetime_start_time < reward.lifetime_time && reward.lifetime_start_time != 0; var end = (reward.lifetime_end_time != -1) ? reward.lifetime_time <= reward.lifetime_end_time && reward.lifetime_end_time != 0 : true; if (start && end) { if (reward.type_id == "100") { var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } else if (reward.type_id == "101") { var amount = reward.amount != 0; if (amount) { state = true; } } else if (reward.type_id == "102") { var percent = reward.percent != 0; if (percent) { state = true; } } else if (reward.type_id == "103") { var percent = reward.percent != 0; var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } } } callback(state); }, checkReward: function(rewardProduct, rewardPointConfig, callback) { var _self = this; _self.consoleLog("checkReward : rewardProduct", rewardProduct); _self.consoleLog("checkReward : rewardPointConfig", rewardPointConfig); var reward = { type_id: "0", amount: 0, percent: 0, every_price: 0 }; _self.checkPointReward(rewardProduct, function(res_state_product) { _self.checkPointReward(rewardPointConfig, function(res_state_point_config) { if (res_state_point_config) { reward.type_id = rewardPointConfig.type_id; reward.type_id = rewardPointConfig.type_id; reward.amount = rewardPointConfig.amount; reward.percent = rewardPointConfig.percent; reward.every_price = rewardPointConfig.every_price; } else if (res_state_product) { reward.type_id = rewardProduct.type_id; reward.amount = rewardProduct.amount; reward.percent = rewardProduct.percent; reward.every_price = rewardProduct.every_price; } _self.consoleLog("checkReward : reward", reward); callback(reward); }); }); }, checkRewardType: function(productReward, shopPointConfig, callback) { var _self = this; _self.momentUnix(function(now) { _self.getProductReward(now, productReward, function(res_reward_product) { _self.getPointConfig(now, shopPointConfig, function(res_reward_point_config) { _self.checkReward(res_reward_product, res_reward_point_config, function(res_reward) { callback(res_reward); }); }); }); }); }, createReward: function(productReward, shopPointConfig, callback) { var _self = this; _self.consoleLog("createReward : productReward", productReward); _self.consoleLog("createReward : shopPointConfig", shopPointConfig); _self.checkRewardType(productReward, shopPointConfig, function(res_reward) { _self.consoleLog("createReward : res_reward", res_reward); callback(res_reward); }); } } return getFunction; }; $scope.getQuantity = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, upDateReward: function() { var _self = this; }, upDateReward: function() { var _self = this; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); }, upDatePrice: function() { var _self = this; var product_price = $scope.data.product_price.price * $scope.data.quantity.quantity_input; var product_compare_price = $scope.data.product_compare_price.price * $scope.data.quantity.quantity_input; $scope.getAttribute().checkPrice(product_price, function(res_price_ecimals) { $scope.data.sum_product_price.price = product_price; $scope.data.sum_product_price.price_ecimals = res_price_ecimals; $scope.getAttribute().checkPrice(product_compare_price, function(res_compare_price_ecimals) { $scope.data.sum_product_compare_price.price = product_compare_price; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((product_compare_price - product_price) > 0) ? product_compare_price - product_price : 0; $scope.getAttribute().checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.upDateReward(); }); }); }); }, input: function(quantityInput) { var _self = this; quantityInput = (quantityInput == null) ? 1 : parseInt(quantityInput); _self.consoleLog("input : quantityInput", quantityInput); if (quantityInput != null) { if (quantityInput >= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_max; } if (quantityInput <= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } } else { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } _self.upDatePrice(); }, minus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input - 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_min", $scope.data.quantity.quantity_min); if (quantity >= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); }, plus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input + 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_max", $scope.data.quantity.quantity_max); if (quantity <= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); } } return getFunction; }; $scope.getBuy = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getProductId: function(params, callback) { var _self = this; var product_id = params.product_id.split("-", 1).join(""); _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, postApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.post(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, UiCartProductAdd: function(productId, quantityInput, promotionId, customOptions, callback) { quantityInput = (quantityInput > $scope.data.quantity.quantity_max) ? $scope.data.quantity.quantity_max : quantityInput; UiCart.delegate.product.add(productId, quantityInput, promotionId, function(res_data) { callback(res_data); }); }, isLogin: function(callback) { var buy_login = $scope._buylogin; var is_login = UiCustomerBox.delegate.get.isLogin(); var is_state = (buy_login) ? (!is_login) ? true : false : false; callback(is_state); }, formLogin: function(is_state, callback) { if (is_state) { $inloginPopup.open(); } callback(is_state); }, getProductStaffId(staff_id_check, callback) { var res_staff_id_check = staff_id_check; var res_staff_id = $scope.dataApi.product.dataArray.product_staff_id; var res_is_state = (res_staff_id != 0 && res_staff_id != '0' && res_staff_id != undefined) ? true : false; callback(res_staff_id_check, res_staff_id, res_is_state); }, isStaffId: function(staff_id_check, callback) { /* todo */ var _self = this; _self.getProductStaffId(staff_id_check, function(res_staff_id_check, res_staff_id, res_is_state) { callback(res_staff_id_check, res_staff_id, res_is_state); }); }, checkCartDuplicateStaff: function(res_staff_id_check, txt_staff_id, res_is_state, callback) { var _self = this var res_is_state = true; if (res_staff_id_check) { var dataSend = { 'txt_staff_id': txt_staff_id, }; _self.dataSend("cart/duplicate_staff", dataSend, function(res_api, res_dataSend) { _self.postApi(res_api, res_dataSend, function(res_ok, res_api, state) { res_is_state = res_api.data.duplicate; callback(res_is_state); }); }); } else { callback(res_is_state); } }, showAlert: function(res_staff_id_check, res_staff_id, res_is_state, res_api, callback) { var res_state = (res_staff_id_check) ? ((res_api) ? ((res_is_state) ? false : true) : true) : false; if (res_state) { if (!res_api) { if (res_staff_id != '0' && res_staff_id != 0) { $scope.controlAlert().alert('002'); } else { $scope.controlAlert().alert('003'); } } else { if (!res_is_state) { $scope.controlAlert().alert('003'); } } } callback(res_state); }, checkStaff: function(callback) { var _self = this var staff_id_check = $scope._checkstaff; var res_check = false; _self.isStaffId(staff_id_check, function(res_staff_id_check, res_staff_id, res_is_state) { _self.checkCartDuplicateStaff(res_staff_id_check, res_staff_id, res_is_state, function(res_api) { _self.showAlert(res_staff_id_check, res_staff_id, res_is_state, res_api, function(res_state) { res_check = res_state; callback(res_check); }); }); }); }, isProgress: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isProgress(productId)) ? true : false; _self.consoleLog("isProgress : productId", productId); _self.consoleLog("isProgress : state", state); callback(state); }, isSelected: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isSelected(productId)) ? true : false; _self.consoleLog("isSelected : productId", productId); _self.consoleLog("isSelected : state", state); callback(state); }, isSelectedReturn: function(productId) { var _self = this; var ui_cart_state = (UiCart.delegate.product.isSelected(productId)) ? true : false; if (!$scope.setBuy.state_active) { $scope.setBuy.state_active = true; var state_process = $scope.setBuy.state_process; var state_step = $scope.setBuy.state_step; if (ui_cart_state && !state_process && state_step != 4) /* cart */ { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else if (!ui_cart_state && !state_process && state_step != 0) /* unset */ { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } else { $scope.setBuy.state_active = false; } } return ui_cart_state; }, updateState: function(productId) { _self = this; _self.isSelected(productId, function(res_state) { if (res_state) { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } return res_state; }); }, uiCart: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; _self.UiCartProductAdd(productId, quantityInput, promotionId, customOptions, function(res_data) { if (res_data) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; if ($scope._cart == "trumpComponentCarts") { _self.trumpComponentCarts(); } }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }, postApiA: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; var custom_options = {}; var dataSend = { 'txt_product_id': productId, 'txt_amount': quantityInput, 'txt_is_clear_cart_before': "0", 'txt_custom_options_json': JSON.stringify(custom_options) }; _self.dataSend("cart/product_add", dataSend, function(res_api, res_dataSend) { _self.postApi(res_api, res_dataSend, function(res_ok, res_api, state) { if (res_ok) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }); }, onProcess: function(data, productId, quantityInput, promotionId, customOptions) { var _self = this; _self.isLogin(function(res_is_login) { _self.formLogin(res_is_login, function(res_form) { _self.checkStaff(function(res_is_state) { if (!$scope.setBuy.state_process && !res_form && !res_is_state) { $scope.setBuy.state_process = true; _self.isSelected(productId, function(res_state) { if (!res_state) { _self.onLoad($scope.setBuy.state_step, function(res_step) { if (data.sum_product_price.price != 0 && data.quantity.quantity_max != 0 && (data.attribute.state == (data.attribute.productId != ''))) { /* UiCart */ _self.uiCart(productId, quantityInput, promotionId, customOptions, res_step); /* api post offline */ /*_self.postApiA(productId, quantityInput, promotionId, customOptions, res_step); */ } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); } else { $scope.setBuy.state_process = false; if ($scope._cart == "trumpComponentCarts") { _self.trumpComponentCarts(); } else if ($scope._cart == "viewcart") { _self.viewCart($scope._cart); } } }); } }); }); }); }, onTimeout: function(time, callback) { var _self = this; var load = $timeout(function() { $timeout.cancel(load); callback(true) }, time); }, onUnset: function(step, callback) { var _self = this; step = (step == 0) ? 0 : 0; $scope.setBuy.state_step = step; callback(step); }, onLoad: function(step, callback) { var _self = this; step = (step == 0 || step == 1) ? 1 : 0; $scope.setBuy.state_step = step; callback(step); }, onPass: function(step, callback) { var _self = this; step = (step == 1 || step == 2) ? 2 : 0; $scope.setBuy.state_step = step; callback(step); }, onError: function(step, callback) { var _self = this; step = (step == 1 || step == 3) ? 3 : 0; $scope.setBuy.state_step = step; callback(step); }, onCart: function(step, callback) { var _self = this; step = (step == 2 || step == 4) ? 4 : 0; $scope.setBuy.state_step = step; callback(step); }, trumpComponentCarts: function() { var controlCart = share.getTrumpComponentCarts(); var component_carts = $('.cover-cards').hasClass('active'); if (!component_carts) { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.cart(); } } else { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.load(); } } }, viewCart: function(viewcart) { var _self = this; _self.pageUrl(viewcart); }, locationUrlReplace: function(page) { $location.url(page).replace(); }, pageUrl: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page); }, main: function(callback) { var _self = this; } } return getFunction; }; $scope.getDetail = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getDetail: function(api, callback) { var _self = this; var description = api.product_description; var info = api.product_more_info; var specificatio = []; if (api.product_attribute.specification_data != undefined) { specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? api.product_attribute.specification_data.pclass_array : []; } var state_specificatio = false; if (api.product_attribute.specification_data != undefined) { state_specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? true : false; } var state_info = (api.product_is_more_info == 1) ? true : false; _self.consoleLog("getDetail : description", description); _self.consoleLog("getDetail : info", info); _self.consoleLog("getDetail : state_info", state_info); _self.consoleLog("getDetail : specificatio", specificatio); _self.consoleLog("getDetail : state_specificatio", state_specificatio); callback(description, info, state_info, specificatio, state_specificatio); }, onClickDetail: function(index) { var _self = this; $scope.data.detail.active = index; _self.consoleLog("onClickDetail : data.detail.active", $scope.data.detail.active); } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageName: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page_name); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.countDown = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getLocation: function(callback) { var _self = this; var res_location = $location; _self.consoleLog("getLocation", "res_location", res_location); callback(res_location); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; _self.consoleLog("getRouteParams", "params", params); callback(params); }, getLocationUrlNameProductDetail: function(callback) { var _self = this; _self.getRouteParams(function(res_params) { _self.getLocation(function(res_location) { var url_page_name = "/product-detail/" + res_params.product_id; var res_url_name_product_detail = (res_location.url() == url_page_name) ? true : false; _self.consoleLog("getLocationUrlNameProductDeal", "res_url_name_product_detail", res_url_name_product_detail); callback(res_url_name_product_detail); }); }); }, getUnix: function(callback) { var _self = this; var now = moment().unix(); _self.consoleLog("getUnix", "now", now); callback(now); }, getCountDown: function(now, product_lifetime, callback) { var _self = this; var countdown_unix = parseInt(product_lifetime.lifetime_end_time) - now; var milliseconds = moment.duration(countdown_unix * 1000, "milliseconds"); var res_countdown = ((milliseconds.days() <= 9) ? '0' + milliseconds.days() : milliseconds.days()); res_countdown = res_countdown + ' : ' + ((milliseconds.hours() <= 9) ? '0' + milliseconds.hours() : milliseconds.hours()); res_countdown = res_countdown + ' : ' + ((milliseconds.minutes() <= 9) ? '0' + milliseconds.minutes() : milliseconds.minutes()); res_countdown = res_countdown + ' : ' + ((milliseconds.seconds() <= 9) ? '0' + milliseconds.seconds() : milliseconds.seconds()); _self.consoleLog("getCountDown", "res_countdown", res_countdown); callback(res_countdown, countdown_unix); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page); }, countDownByProduct: function(now, data_array, callback) { var _self = this; if (data_array.length != 0) { if (data_array.product_lifetime.length != 0) { _self.getCountDown(now, data_array.product_lifetime, function(res_count_down, res_countdown_unix) { data_array.product_lifetime.lifetime_countdown = (res_countdown_unix > 0) ? res_count_down : ""; if (data_array.product_lifetime.lifetime_countdown == "") { _self.getNameUrl(data_array.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", data_array.product_set_array[0].product_id, res_name); }); } }); } } _self.consoleLog("countDownByProduct", "data_array", data_array); callback(data_array); }, loop: function() { var _self = this; var load = $timeout(function() { $timeout.cancel(load); _self.getUnix(function(res_now) { _self.countDownByProduct(res_now, $scope.dataApi.product.dataArray, function(data_array) { $scope.dataApi.product.dataArray = data_array; _self.getLocationUrlNameProductDetail(function(res_url_name_product_detail) { if (res_url_name_product_detail) { _self.loop(); } }); }); }); }, 1000); } } return getFunction; }; $scope.getPromotion = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, setPromotionId: function(promotion_id) { var _self = this; _self.consoleLog("setPromotionId", "promotion_id", promotion_id); $scope.data.promotion.promotion_id = promotion_id; _self.consoleLog("setPromotionId", "data.promotion.promotion_id", $scope.data.promotion.promotion_id); }, } return getFunction; }; $scope.control = function() { var getFunction = { popupVideo: function(state, video_link, video_embed_code) { var _self = this; if (video_embed_code != '') { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } else if (video_link != '') { window.open(video_link, '_blank'); } else { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } }, main: function() { var _self = this; } } return getFunction; }; $scope.data_control = { page_video: { popup: false, shop_video_embed_code: "" } } $scope.control_alert = { alert: { error_id: '', index: null, state: true, error: [{ id: '001', title: 'การสั่งซื้อ', messages: 'สามารถสั่งซื้อได้เพียงทีละออเดอร์เท่านั้น' }, { id: '002', title: 'การเพิ่มสินค้า', messages: 'ไม่สามารถเพิ่มสินค้าของร้านมากกว่า 1 ร้านค้าได้' }, { id: '003', title: 'การสั่งซื้อ', messages: 'ไม่สามารถเพิ่มสินค้า(ไม่มีร้านค้า)' }] } }; $scope.controlAlert = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getErrorMessages: function(error_id, callback) { var _self = this; var messages = { res_error_id: '', res_index: null } angular.forEach($scope.control_alert.alert.error, function(item, index) { if (item.id == error_id) { messages.res_error_id = item.id; messages.res_index = index; } }); callback(messages.res_error_id, messages.res_index); }, alert: function(error_id) { var _self = this; _self.getErrorMessages(error_id, function(res_error_id, res_index) { $scope.control_alert.alert.error_id = res_error_id; $scope.control_alert.alert.index = res_index; $scope.control_alert.alert.state = (!$scope.control.alert && res_error_id != '') ? true : false; }); }, main: function() { var _self = this; } } return getFunction; }; $scope.countDown().loop(); /* set carousel */ $scope.setCarousel = { carousel: 0, index: 0 }; $scope.getCarousel().getCarousel($scope.setCarousel.carousel, function(res_carousel_id) { $scope.setCarousel.carousel = res_carousel_id; }); /* set carousel */ /* get product api */ $scope.dataApi = { reward: { dataSend: {}, api: "shop/current", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, staff: { dataSend: { txt_staff_id: 0 }, api: "staff/id", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, product: { dataSend: { txt_product_id: 0 }, api: "product/id", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, relation: { dataSend: { txt_referral_id: 0 }, api: "referral/relation", ok: false, dataArray: [], dataArrayState: { load: false, done: false } } }; $scope.data = { attribute: { state: false, productId: "", dataArray: [] }, attribute_custom: { state: false, dataArray: [] }, reward: { quantity_name: 'reward', type_id: "0", reward_amount: 0, reward_percent: 0, reward_every_price: 0, point_reward: 0 }, quantity: { quantity_name: 'quantity', quantity_min: 1, quantity_max: 1, quantity_input: 1, quantity_select: [] }, product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, detail: { active: '0', dataArray: [{ index: '0', state: true, en: ($scope.description != undefined && $scope.description != "") ? $scope.description : 'Description', th: 'ภาพรวม', data: '', dataArray: [] }, { index: '1', state: true, en: ($scope.info != undefined && $scope.info != "") ? $scope.info : 'Info', th: 'ข้อมูล', data: '', dataArray: [] }, { index: '2', state: true, en: ($scope.specification != undefined && $scope.specification != "") ? $scope.specification : 'Specification', th: 'สเปค', data: '', dataArray: [] }, { index: '3', state: true, en: '', th: 'คลังรูปภาพ/วิดีโอ', data: '', dataArray: [] }, { index: '4', state: true, en: '', th: 'พูดคุยผู้ใช้', data: '', dataArray: [] }] }, promotion : { promotion_id : '0' } }; $scope.setBuy = { state_active: false, state_process: false, state_step: 0, state_data_font_color: "", state_data_background_color: "", stepArray: [{ step: 0, name: "unset", icon: $scope._icebuyicon, state: $scope._buytext, data_font_color: "", data_background_color: "" }, { step: 1, name: "load", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 2, name: "pass", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 3, name: "error", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 4, name: "cart", icon: "", state: $scope._viewcarttext, data_font_color: "", data_background_color: "primary_darkest" }] }; /* - get api product/id start - */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.product.dataArrayState = res_state; $scope.getData().getProductId(res_params, function(res_product_id) { $scope.dataApi.product.dataSend.txt_product_id = (res_product_id != false) ? res_product_id : 0; $scope.getData().dataSend($scope.dataApi.product.api, $scope.dataApi.product.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_product, res_state) { $scope.dataApi.product.ok = res_ok; if ($scope._imageappcoverchecked) { var images = []; angular.forEach(get_res_api_product.data.product_image,function(image,index_image){ if (!image.image_app_cover_checked) { images.push(image) } }); get_res_api_product.data.product_image = images; } $scope.dataApi.product.dataArray = get_res_api_product.data; $scope.getData().consoleLog("get_res_api_product", get_res_api_product); $scope.dataApi.product.dataArrayState = res_state; /* -- get api shop/current to reward -- */ if (res_ok) { $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.reward.dataArrayState = res_state; $scope.getData().dataSend($scope.dataApi.reward.api, $scope.dataApi.reward.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_shop, res_state) { $scope.dataApi.reward.ok = res_ok; $scope.dataApi.reward.dataArray = get_res_api_shop.data; $scope.dataApi.reward.dataArrayState = res_state; $scope.getReward().createReward($scope.dataApi.product.dataArray.product_reward, get_res_api_shop.data.shop_point_config, function(res_reward) { $scope.data.reward.type_id = res_reward.type_id; $scope.data.reward.reward_amount = res_reward.amount; $scope.data.reward.reward_percent = res_reward.percent; $scope.data.reward.reward_every_price = res_reward.every_price; /* --- Wait product/id ,shop/current --- */ /* ---- get attribute ---- */ $scope.getAttribute().productAttribute(get_res_api_product.data.product_attribute, function(res_attribute) { $scope.data.attribute.dataArray = res_attribute; $scope.getAttribute().checkMinPrices(get_res_api_product, res_attribute, function(res_data_price, res_state) { $scope.data.attribute.state = res_state; $scope.data.product_price = res_data_price.product_price; $scope.data.product_compare_price = res_data_price.product_compare_price; $scope.data.sum_product_price = res_data_price.sum_product_price; $scope.data.sum_product_compare_price = res_data_price.sum_product_compare_price; $scope.data.sum_product_compare_minus_sum_product_price = res_data_price.sum_product_compare_minus_sum_product_price; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); /* ----- stock ----- */ $scope.data.quantity.quantity_max = res_data_price.product_price.total_stock; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_data_price.product_price.total_stock; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* ----- stock ----- */ }); }); /* ---- get attribute ---- */ /* ---- get attribute custom ---- */ $scope.getAttributeCustom().createArray(get_res_api_product.data.product_custom_templates, function(res_custom_attribute, res_state) { $scope.data.attribute_custom.state = res_state; $scope.data.attribute_custom.dataArray = res_custom_attribute; }); /* ---- get attribute custom ---- */ /* ---- get detail ---- */ $scope.getDetail().getDetail(get_res_api_product.data, function(res_description, res_info, res_state_info, res_specificatio, res_state_specificatio) { $scope.data.detail.dataArray[0].data = res_description; $scope.data.detail.dataArray[1].data = res_info; $scope.data.detail.dataArray[1].state = res_state_info; $scope.data.detail.dataArray[2].dataArray = res_specificatio; $scope.data.detail.dataArray[2].state = res_state_specificatio; }); /* ---- get detail ---- */ /* ---- update state ---- */ $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); /* ---- update state ---- */ /* --- Wait product/id ,shop/current --- */ }); }); }); }); /* -- get api shop/current to reward -- */ /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.relation.dataArrayState = res_state; $scope.getData().getReferralId(get_res_api_product.data.product_referral_display, function(res_referral_id) { $scope.dataApi.relation.dataSend.txt_referral_id = res_referral_id; $scope.getData().dataSend($scope.dataApi.relation.api, $scope.dataApi.relation.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_referral, res_state) { $scope.dataApi.relation.ok = res_ok; $scope.dataApi.relation.dataArray = (res_referral_id != 0) ? get_res_api_referral.data : []; $scope.dataApi.relation.dataArrayState = res_state; }); }); }); }); /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ /* -- product_staff_id from product/id to txt_staff_id get api staff/id -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.getData().getStaffId(get_res_api_product.data.product_staff_id, function(res_staff) { if (res_staff.status) { $scope.dataApi.staff.dataArrayState = res_state; $scope.dataApi.staff.dataSend.txt_staff_id = res_staff.staff_id; $scope.getData().dataSend($scope.dataApi.staff.api, $scope.dataApi.staff.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, res, res_state) { $scope.dataApi.staff.ok = res_ok; $scope.dataApi.staff.dataArray = res.data; $scope.getData().getNameUrl(res.data.staff_first_name, function(res_staff_first_name_url) { $scope.dataApi.staff.dataArray.staff_first_name_url = res_staff_first_name_url; $scope.dataApi.staff.dataArrayState = res_state; }); }); }); } }); }); /* -- product_staff_id from product/id to txt_staff_id get api staff/id -- */ } else { /* ok = false */ if ($scope.dataApi.product.dataArray.length != 0) { /* product deal to product original */ if ($scope.dataApi.product.dataArray.product_set_array.length != 0) { $scope.countDown().getNameUrl($scope.dataApi.product.dataArray.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", $scope.dataApi.product.dataArray.product_set_array[0].product_id, res_name); }); } else { $scope.pages().pageName("home"); } } else { /* product null */ $scope.pages().pageName("home"); } } }); }); }); }); /* - get api product/id end - */ /* get product api */ }; return promise; });_ui_share_app.directive('productDetailPageX', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageX'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.qtyProduct = 1; $scope.data = false; $scope.dataPreserve = false; $scope._data_qty_model = 1; $scope._data_qty_selected = 1; $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; var dataSend = { 'txt_product_id': $scope._getPostIdFromURL(), }; if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/id", { params: dataSend }).then(function(res) { var e = res.data; if (e.ok == 1) { console.log("product_set_array : data", e.data); $scope.data = e.data; $scope.dataPreserve = e.data; $scope._getSupportDataCategory('category', e.data); $scope.buildDataProductRelate($scope._getPostIdFromURL()); console.log("product_set_array : data", e.data); if (typeof $scope.data.product_attribute.option_data !== 'undefined' && $scope.data.product_total_variant > 0) { if (typeof $scope.data.product_attribute.option_data.pclass_array !== 'undefined' && $scope.data.product_attribute.option_data.pclass_array.length) { $scope.buildVariantOption(e.data); } } if (res.data.product_attribute.length != 0) { $scope.buildMultipleQuantity(res.data); } } }); } else { $componentProductDetail.get('product/id', { 'txt_product_id': $scope._getPostIdFromURL() }, function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; $scope._getSupportDataCategory('category', e.data); $scope.buildDataProductRelate($scope._getPostIdFromURL()); if (typeof $scope.data.product_attribute.option_data !== 'undefined' && $scope.data.product_total_variant > 0) { if (typeof $scope.data.product_attribute.option_data.pclass_array !== 'undefined' && $scope.data.product_attribute.option_data.pclass_array.length) { $scope.buildVariantOption(e.data); } } if (e.data.product_attribute.length != 0) { $scope.buildMultipleQuantity(e.data); } } }); } $scope.productQuantityMultiArray = []; $scope.lastCheckedVariantKey = ''; $scope.buildMultipleQuantity = function(productObj) { $scope.productQuantityMultiArray = []; var r = [], p = productObj.product_attribute.option_data.variant_array; for (var i = 0; i < p.length; i++) { if (p[i].status == 1 && p[i].status == 1) { $scope.productQuantityMultiArray.push({ v_key: p[i].variant_key, v_name: p[i].option_name_array[0], v_qty: 1, v_active: 0 }); } } }; $scope.currentOptionQtyPick = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } return e.val(); }; $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id) { var j = { 'relate_product_id_array': [product_id], 'badge_id_array': [18] }; var d = { 'cur_page': 1, 'per_page': 8, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists', d).then(function(e) { if (e.ok == 1) { var d = []; angular.forEach(e.data.dataList, function(item) { if (item.product_id !== $scope.data.product_id) { d.push(item); } }); $scope.dataRelate = d; } }); }; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { $scope.buildDataProductRelate($scope._getPostIdFromURL()); if (objectData.product_total_variant <= 0) { /*return;*/ } if (typeof $scope.data.product_attribute.option_data !== 'undefined' && $scope.data.product_total_variant > 0) { if (typeof $scope.data.product_attribute.option_data.pclass_array !== 'undefined' && $scope.data.product_attribute.option_data.pclass_array.length) { $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; } } }; $scope.ifOptionUnSelect = function() { return ($('.d_qty_price.active.inin').length > 0) ? true : false; }; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; }; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $('.d_qty_not_result').removeClass("active"); $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { if ($index == 0 && option_id == '') { return $componentProductDetail.get('product/id', { 'txt_product_id': $scope._getPostIdFromURL() }, function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; $scope.switchQuantityByKey('-' + variantsPick.join('-') + '-'); break; } } }; $scope.switchQuantityByKey = function(variant_key) { $scope.lastCheckedVariantKey = variant_key; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price[variant-key!="' + variant_key + '"]').removeClass('active').removeClass('inin'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('active'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('active'); $timeout(function() { $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('inin'); }, 300); }; $rootScope.$on('repeatend', function() { /* Slider Send */ var optionsParmas = { autoplay: true, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, infinite: true }; var extraOptions = { animate: false }; $timeout(function() { sliderProvider("#gallery_slider", optionsParmas, "", "", extraOptions); }, 500); }); /* Slick Events */ $scope._slickGoLeft = function() { $timeout(function() { $('#gallery_slider').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('#gallery_slider').slick('slickNext'); }, 100); }; /* Click SLick Item */ $scope.slickGoto = function(idx) { $timeout(function() { $('#gallery_slider').slick('slickGoTo', idx); }, 100); }; /* Calcu Nav Arrows */ $scope.navArrowsCalculate = function() { var size = (500 / 2); var n = (size + 18) + 20; return '-' + n + 'px'; }; $scope.navArrowWidth = function() { return $('#gallery_slider').width() + 'px'; }; /* Build title for Address link*/ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* Calculate discount (simple mode) * @params {expensivePrice} * @params {salePrice} * @return int */ $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; $scope.support_data = { category: [], }; $scope._getSupportDataCategory = function(type, data) { var dataSend = { 'txt_referral_id': data.product_referral_display.category[0].referral_id }; GAEAPI.get('referral/relation', dataSend).then(function(e) { if (e.ok == 1) { $scope.support_data.category = e.data; } }); }; /* Optimize image size by device pixel * @params {size} (integer) prefer size * @params {image_url} (string) original image source link * @params {image_width} (string) original image width * @return string */ $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; /* Hide when visible badge */ $scope.exceptVisibleBadge = function(objectItem) { var r = parseInt(objectItem.badge_id); var s = false; switch (r) { case 16: case 72: case 74: case 75: s = true; break; default: s = false; break; } return s; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; $scope.invited = []; $scope.insertinvited = function(user) { if (user) { if (user.product_attribute.length != 0) { if ($scope.invited[0] == user.product_id) { return; } $scope.invited.push(user.product_id); } else { alert("item can't compare"); } } else { console.log("test_array :", $scope.invited); } }; /* Display Badge Name */ $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 16: str = "FEATURED"; break; case 72: str = "NEW"; break; case 74: str = "RECOMMEND"; break; case 75: str = "BEST SELLER"; break; case 82: str = "NEW (App)"; break; case 83: str = "RECOMMEND (App)"; break; case 84: str = "BEST SELLER (App)"; break; } return str; }; $scope.renderBadgeTypeImg = function() { var returnData = false; if (CUR_THEME.shop_id() == "717") { returnData = true; } else { returnData = false; } return returnData; }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; }; return promise; });_ui_share_app.directive('productDetailPageXa', function($rootScope, $routeParams, sliderProvider, $componentProductDetail, $location) { var templateName = 'productDetailPageXa'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', imgcart: '@imgcart', view: '@viewcart', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; if ($scope.imgcart != undefined) { $scope.setimg_cart = $scope.icnPath + $scope.imgcart; } $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; /*if ($scope._dataArray.product_hightlight_video_embed != "") { $scope._dataArray.product_image.unshift({ image_url: $scope.imgPath + 'img-play.png', product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed }); }*/ $scope._dataArrayRelateProductId = res.data.product_id; if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.productRelateTag($scope._dataArray.product_tags); $scope.buildVariantOption(res.data); if (res.data.product_attribute.length != 0) { $scope.buildMultipleQuantity(res.data); } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '#gallery_slider[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope._data_qty_selected = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.onSelectVariantItems(0, ''); }; $scope.dataVariantsPick = []; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $timeout.cancel(s); $('select.variantSelector').each(function(idx, obj) { var optionElementFirst = $(this).find('option[data-index="' + idx + '"]').eq(0); optionElementFirst.prop("selected", true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var _self = dataVariants[i]; var _self_option = angular.fromJson(_self.option_id_json); var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope.switchQuantityByKey('-' + variantsPick.join('-') + '-'); console.log("selectedOptionTextJson: option", _self); if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope._dataArray.product_image.length; im++) { if ($scope._dataArray.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } $timeout(function() { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { $scope._slickGoto('gallery_show', rightImagePosition); } else { angular.element('.gallery-thumbnail .thumb-img[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300); } break; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.currentOptionQtyPick = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } return e.val(); }; $scope.switchQuantityByKey = function(variant_key) { $scope.lastCheckedVariantKey = variant_key; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price[variant-key!="' + variant_key + '"]').removeClass('active').removeClass('inin'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('active'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('active'); $timeout(function() { $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('inin'); }, 300); }; $scope.productQuantityMultiArray = []; $scope.lastCheckedVariantKey = ''; $scope.buildMultipleQuantity = function(productObj) { $scope.productQuantityMultiArray = []; var r = [], p = productObj.product_attribute.option_data.variant_array; for (var i = 0; i < p.length; i++) { if (p[i].status == 1 && p[i].status == 1) { $scope.productQuantityMultiArray.push({ v_key: p[i].variant_key, v_name: p[i].option_name_array[0], v_qty: 1, v_active: 0 }); } } }; $scope.dataVariantsPick = []; $scope.electric = []; $scope.testyuyu = 0; $scope.onSelectVariantItems = function($index, option_id) { $scope.testyuyu = 0; if (option_id == '') { $scope.testyuyu = 0; $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_not_result').addClass("active"); $scope.dataVariantsPick[$index] = option_id; console.log("check_vareian 1000:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length); return GAEAPI.get('product/id', { 'txt_product_id': $scope._idUrl($scope._viewRouteParams().product_id) }).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; for (var i = 0; i < $scope.dataVariantsPick.length; i++) { if ($scope.dataVariantsPick[i] != undefined && $scope.dataVariantsPick[i] != "") { $scope.testyuyu++; } } if ($scope.testyuyu >= $scope.dataOption.length) { $scope.testyuyu = 0; $('.d_qty_not_result').removeClass("active"); $scope.findVariantsData($scope.dataVariantsPick); } else { $scope.testyuyu = 0; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); } console.log("check_vareian 1001:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length, $scope.electric); } }; $scope.ifOptionUnSelect = function() { return ($('.d_qty_price.active.inin').length > 0) ? true : false; }; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('productDetailPageZ', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageZ'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', iconbuy: '@iconbuy', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.login = function() { var login = { showLogin: function() { return UiCustomerBox.delegate.get.isLogin(); }, isLogin: function(callback) { callback(UiCustomerBox.delegate.get.isLogin()); }, totalAmount: function() { return UiCart.delegate.get.totalAmount() || 0; }, pageLogin: function() { var _self = this; _self.isLogin(function(isLogin) { if (!isLogin) { $inloginPopupTypeGrip.open(); } }); } } return login; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d, $scope).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope._dataArray_tag = []; $scope._dataArray = []; $scope.data_min = []; $scope._dataArrayState = { load: false, done: false }; $scope.names = []; $scope.currentStock = 0; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.encodeURIComponentOut = function(str) { var output = encodeURIComponent(str); return output; }; $scope.checkPrice = function(price) { var check_price = 0; var _price = (price != undefined && price != "" && price != null) ? price.toString() : "0"; if (_price.includes(".")) { check_price = 2; } return check_price; }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend, $scope).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; /*if ($scope._dataArray.product_hightlight_video_embed != "") { $scope._dataArray.product_image.unshift({ image_url: $scope.imgPath + 'img-play.png', product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed }); }*/ $('.gallery_container').css('height', '0'); $('.gallery_container').css('opacity', '0'); setTimeout(function() { $('.gallery_container').css('height', 'auto'); $('.gallery_container').css('opacity', '1'); }, 2000); $scope._dataArrayRelateProductId = res.data.product_id; if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } /*if ($scope._dataArray.product_description == '') { $scope._viewTab(2); }*/ $scope.names = []; if (res.data.product_total_variant == 0 && res.data.product_total_stock > 0) { for (var i = 0; i < parseFloat(res.data.product_total_stock); i++) { $scope.names.push(i + 1); } } if (res.data.product_total_variant == 0 && res.data.product_total_stock < 0) { for (var i = 0; i < 20; i++) { $scope.names.push(i + 1); } } if (res.data.product_total_variant > 0) { for (var i = 0; i < 20; i++) { $scope.names.push(i + 1); } } if (res.data.product_attribute != undefined) { if (res.data.product_attribute.option_data != undefined) { if (res.data.product_attribute.option_data.variant_array != undefined) { if (res.data.product_attribute.option_data.variant_array.length != 0) { var set_varia = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseFloat(set_varia) >= parseFloat(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } } } } } $scope._dataArray_tag = res.data.product_tags.split(","); $scope.buildMultipleQuantity(res.data); $scope.buildVariantOption(res.data); // $scope.builldRelateProduct(res.data); $scope.currentStock = $scope._dataArray.product_total_stock; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.dataRelateProductArray = []; $scope.builldRelateProduct = function(dataObj) { console.log("_getDataArray", dataObj); var dataSend = { 'cur_page': 1, 'per_page': 5, 'txt_filter_json': JSON.stringify({ "badge_id_array": [18], "tags": dataObj.product_tags }) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.dataRelateProductArray = e.data.dataList; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVaraintsClick_Normal(); }; $scope.dataVariantsPick = []; $scope.onClickVariantItems = function($index, option_id) { console.log("onClickVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.nowMoment = moment().unix(); $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope.saleprice = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } return (calculate > 0) ? calculate : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.stateShow = false; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var count = 0; var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); var _self = dataVariants[i]; var _self_option = angular.fromJson(_self.option_id_json); var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope.data.product_total_stock = dataVariants[i].total_stock; console.log("tasdasdasdasest if", $scope.data.product_total_stock); $scope.names = []; if (parseFloat($scope.data.product_total_stock) == 0) { $scope.stateShow = false; $scope.names = [1];  } else { $scope.stateShow = true; for (var i = 0; i < parseFloat($scope.data.product_total_stock); i++) { $scope.names.push(i + 1); } } console.log("selectedOptionTextJson: option", _self); if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope.data.product_image.length; im++) { if ($scope.data.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } $timeout(function() { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { $scope.slickGoto('gallery_show', rightImagePosition); } else { angular.element('.gallery-thumbnail .thumb-img[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300); } break; } else { console.log("tasdasdasdasest else", $scope.data.product_total_stock); $scope.stateShow = false; } if (!compareArray(variantsPick, optionJson)) {                     count++;               }                 if (count >= dataVariants.length) {  $scope._dataArray.product_id = dataVariants[i].product_id;                                        console.log("optionJson : 0000 ", count, dataVariants[i].total_stock);   $scope.names = [1];        $scope.stateShow = false;                      } } }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); /*$(".cover_image_item_md_lg").css("height", $(".cover_image_item_md_lg").css("width")); $(".gallery_display_md_lg").css("height", $(".cover_image_item_md_lg").css("width"));*/ $("iframe").css("height", $(".cover_image_item_md_lg").css("width")); $("iframe").css("width", $(".cover_image_item_md_lg").css("width")); } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { /*$scope.returnheight(); $scope.timeCountStart();*/ }, 1000); } $scope.timeCountStart(); $scope.data_viewTab = '1'; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope._data_qty_model = 1; $scope._data_qty_selected = 1; $scope.currentOptionQtyPick = function(variant_key) { if ($('#detail_qty[variant-key="' + variant_key + '"]').val() != undefined) { var e = parseFloat($('#detail_qty[variant-key="' + variant_key + '"]').val().substr(7)); } return e; }; $scope.watchQty = function(variant_key) { var e = angular.element('select[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('select[name="detail_qty"][variant-key="' + variant_key + '"]'); } if ($('#detail_qty[variant-key="' + variant_key + '"]').val() != undefined) { $scope._data_qty_selected = parseFloat($('#detail_qty[variant-key="' + variant_key + '"]').val().substr(7)); } console.log("_data_qty_selected", $scope._data_qty_selected); /* parseFloat(e.val()); alert(i);onSelectVariantItems*/ if ($scope._data_qty_selected <= 0 || typeof $scope._data_qty_selected == 'undefined' || isNaN($scope._data_qty_selected)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.productQuantityMultiArray = []; $scope.lastCheckedVariantKey = ''; $scope.buildMultipleQuantity = function(productObj) { $scope.productQuantityMultiArray = []; var r = []; if (productObj.product_attribute.option_data != undefined && productObj.product_attribute.option_data.length > 0) { var p = productObj.product_attribute.option_data.variant_array; for (var i = 0; i < p.length; i++) { if (p[i].status == 1 && p[i].status == 1) { $scope.productQuantityMultiArray.push({ v_key: p[i].variant_key, v_name: p[i].option_name_array[0], v_qty: 1, v_active: 0 }); } } } }; $scope.switchQuantityByKey = function(variant_key) { $scope.lastCheckedVariantKey = variant_key; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price[variant-key!="' + variant_key + '"]').removeClass('active').removeClass('inin'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('active'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('active'); $timeout(function() { $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('inin'); }, 300); }; $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").find('select').val() != undefined) { check_int = parseFloat($(".d_qty").find('select').val().substr(7)); } return check_int; }; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; }; $scope.outofstock = 0; $scope.getOutofstock = function() { $scope.outofstock = 1; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.onSelectVariantItems(0, ''); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { $scope.testyuyu = 0; if (option_id == '') { $scope.names = []; for (var i = 0; i < 20; i++) { $scope.names.push(i + 1); } $scope._dataArray.product_id = $scope._idUrl($scope._viewRouteParams().product_id); $scope._dataArray.product_price = $scope.data_min.price; $scope.testyuyu = 0; $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); $('.d_qty').removeClass('active').removeClass('inin'); $('.dsetting').addClass("active"); $('.d_qty_not_result').addClass("active"); $scope.dataVariantsPick[$index] = option_id; console.log("check_vareian 1000:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length); return GAEAPI.get('product/id', { 'txt_product_id': $scope._idUrl($routeParams.product_id) }, $scope).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; for (var i = 0; i < $scope.dataVariantsPick.length; i++) { if ($scope.dataVariantsPick[i] != undefined && $scope.dataVariantsPick[i] != "") { $scope.testyuyu++; console.log("check_vareian 103", $scope.testyuyu); } } if ($scope.testyuyu >= $scope.dataOption.length) { console.log("check_vareian 104", $scope.testyuyu); $scope.testyuyu = 0; $scope.findVariantsData($scope.dataVariantsPick); $(".d_qty").find('select').val("number:1"); } else { console.log("check_vareian 105", $scope.testyuyu); $scope.testyuyu = 0; $(".d_qty").find('select').val("number:1"); } console.log("check_vareian 1001:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length, $scope.electric, $scope.testyuyu); } /*alert($scope.dataVariantsPick);*/ }; $scope.video_code = ""; $scope.videoShow = function() { $scope.video_code = $scope._dataArray.product_hightlight_video_embed; $(".videoHighlightOverlay").addClass("active"); console.log("videoShow"); } $scope.videoHide = function() { $scope.video_code = ''; $(".videoHighlightOverlay").removeClass("active"); console.log("videoHide"); } $scope.viewHide = function(arrayData, optionData) { var reTest = false; if (optionData == arrayData.length) { for (var i = 0; arrayData.length > i; i++) { console.log("arrayData[i]", arrayData[i]); if (!arrayData[i]) { reTest = false; break; } else { reTest = true; } } } return reTest; } $scope.viewHideOp = function(arrayData, optionData) { var e = false; if (optionData == 0 && arrayData.length == 0) { e = true; } return e; } $scope.qtuC = function() { var e = 1; if ($(".d_qty").find('select').val() == "") { $(".d_qty").find('select').val("number:1"); var e = 1; } else { var e = $(".d_qty").find('select').val(); } return e; } $scope.buyC = function() { var e = false; if ($scope.dataOption.length == 0 && $scope.viewHide($scope.dataVariantsPick, $scope.dataOption.length) == false) { if ($scope.names.length == 0) { e = false } else { e = true; } } else if ($scope.dataOption.length > 0) { if ($scope.viewHide($scope.dataVariantsPick, $scope.dataOption.length) == true) { if ($scope.stateShow == true) { e = true; } } else { e = false; } } return e; } $scope.outOfStockShow = function() { var e = false; if ($scope.buyC() == true) { e = true; } else { if ($scope.names.length == 20) { e = true; } else { e = false; } } return e; } }; return promise; });_ui_share_app.directive('productDetailPageZa', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailPageZa'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { buttonicon: '@buttonicon', buttontext: '@buttontext', stylebutton: '@stylebutton', promotelink: '@promotelink', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._stylebutton = ($scope.stylebutton == undefined || $scope.stylebutton == "") ? 'filled_button_round_small' : $scope.stylebutton; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; /* add data video */ /*if ($scope._dataArray.product_hightlight_video_embed != "") { $scope._dataArray.product_image.unshift({ image_url: $scope.imgPath + 'img-play.png', product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed }); }*/ /* add data video */ $scope._dataArrayRelateProductId = res.data.product_id; if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.productRelateTag($scope._dataArray.product_tags); $scope.buildVariantOption(res.data); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = '1'; $scope.viewQuantity = function() { /*return $(".d_qty.active.inin").find('input').val() || 1;*/ return $( "#d_qty option:selected" ).text(); }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVaraintsClick_Normal(); }; $scope.dataVariantsPick = [""]; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.dataVariantsPick = [""]; $scope.onSelectVariantItems = function($index, option_id){ console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if($scope.dataVariantsPick.length >= $scope.dataOption.length){ $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.makeVariantsClick = function(){ var s = $timeout(function(){ $timeout.cancel(s); $('select.variantSelector').each(function(idx,obj){ var optionElementFirst = $(this).find('option[data-index="'+idx+'"]').eq(0); optionElementFirst.prop("selected",true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; /* Change Big Image when click thumbnail */ $scope.dataChangeBigImage = 0; $scope.changeBigImage = function(dataObject,index) { $scope.dataChangeBigImage = index; $timeout(function() { var e = $('.gallery-display'); var el = $('.gallery-display').find('img').eq(0); e.css('opacity', '0'); $timeout(function() { el.attr('original-src', el.attr('src')); el.attr('src', dataObject.image_url); el.addClass('has-changed'); e.css('opacity', '1'); }, 600); }, 300); }; }; return promise; });_ui_share_app.directive('productDetailPageZb', function($rootScope, $routeParams, sliderProvider, $componentProductDetail, $location) { var templateName = 'productDetailPageZb'; var componentMain = 'componentProductDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', iconbuy: '@iconbuy', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.login = function() { var login = { showLogin: function() { return UiCustomerBox.delegate.get.isLogin(); }, isLogin: function(callback) { callback(UiCustomerBox.delegate.get.isLogin()); }, pageLogin: function() { var _self = this; _self.isLogin(function(isLogin) { if (!isLogin) { /* $location.url('member').replace(); */ window.location.href = "member"; } }); } } return login; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.titleUrl = function(str) { var res_str = ''; if (str != undefined) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); res_str = s.toLowerCase(); } return res_str; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope._dataArray_tag = {}; $scope._dataArray = []; $scope.data_min = []; $scope._dataArrayState = { load: false, done: false }; $scope.names = []; $scope.currentStock = 0; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { console.log("productDetailPageZb : res : ", res); $scope._dataArray = res.data; /*if ($scope._dataArray.product_hightlight_video_embed != "") { $scope._dataArray.product_image.unshift({ image_url: $scope.imgPath + 'img-play.png', product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed }); }*/ $scope._dataArrayRelateProductId = res.data.product_id; if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } /*if ($scope._dataArray.product_description == '') { $scope._viewTab(2); }*/ $scope.names = []; if (res.data.product_total_variant == 0 && res.data.product_total_stock > 0) { for (var i = 0; i < parseInt(res.data.product_total_stock); i++) { $scope.names.push(i + 1); } } if (res.data.product_total_variant == 0 && res.data.product_total_stock < 0) { for (var i = 0; i < 20; i++) { $scope.names.push(i + 1); } } if (res.data.product_total_variant > 0) { for (var i = 0; i < 20; i++) { $scope.names.push(i + 1); } } if (res.data.product_attribute != undefined) { if (res.data.product_attribute.option_data != undefined) { if (res.data.product_attribute.option_data.variant_array != undefined) { if (res.data.product_attribute.option_data.variant_array.length != 0) { var set_varia = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } } } } } $scope._dataArray_tag = res.data.product_tags.split(","); $scope.buildMultipleQuantity(res.data); $scope.buildVariantOption(res.data); $scope.builldRelateProduct(res.data); $scope.currentStock = $scope._dataArray.product_total_stock; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.dataRelateProductArray = []; $scope.builldRelateProduct = function(dataObj) { console.log("_getDataArray", dataObj); var dataSend = { 'cur_page': 1, 'per_page': 5, 'txt_filter_json': JSON.stringify({ "badge_id_array": [18], "tags": dataObj.product_tags }) }; GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok === 1) { $scope.dataRelateProductArray = e.data.dataList; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVaraintsClick_Normal(); }; $scope.dataVariantsPick = []; $scope.onClickVariantItems = function($index, option_id) { console.log("onClickVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.nowMoment = moment().unix(); $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope.saleprice = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } return (calculate > 0) ? calculate : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, lifetime_start_time, lifetime_end_time, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined && lifetime_start_time <= $scope.nowMoment && (lifetime_end_time == -1 || lifetime_end_time >= $scope.nowMoment)) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.stateShow = false; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var count = 0; var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); var _self = dataVariants[i]; var _self_option = angular.fromJson(_self.option_id_json); var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { console.log("dataVariants : ", dataVariants); $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope.data.product_total_stock = dataVariants[i].total_stock; console.log("tasdasdasdasest if", $scope.data.product_total_stock); $scope.names = []; if (parseInt($scope.data.product_total_stock) == 0) { $scope.stateShow = false; $scope.names = [1];  } else { $scope.stateShow = true; for (var i = 0; i < parseInt($scope.data.product_total_stock); i++) { $scope.names.push(i + 1); } } console.log("selectedOptionTextJson: option", _self); if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope.data.product_image.length; im++) { if ($scope.data.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } $timeout(function() { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { $scope.slickGoto('gallery_show', rightImagePosition); } else { angular.element('.gallery-thumbnail .thumb-img[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300); } break; } else { console.log("tasdasdasdasest else", $scope.data.product_total_stock); $scope.stateShow = false; } if (!compareArray(variantsPick, optionJson)) {                     count++;               }                 if (count >= dataVariants.length) {  $scope._dataArray.product_id = dataVariants[i].product_id;                                        console.log("optionJson : 0000 ", count, dataVariants[i].total_stock);   $scope.names = [1];        $scope.stateShow = false;                      } } }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); /*$(".cover_image_item_md_lg").css("height", $(".cover_image_item_md_lg").css("width")); $(".gallery_display_md_lg").css("height", $(".cover_image_item_md_lg").css("width"));*/ $("iframe").css("height", $(".cover_image_item_md_lg").css("width")); $("iframe").css("width", $(".cover_image_item_md_lg").css("width")); } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { /*$scope.returnheight(); $scope.timeCountStart();*/ }, 1000); } $scope.timeCountStart(); $scope.data_viewTab = '1'; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope._data_qty_model = 1; $scope._data_qty_selected = 1; $scope.currentOptionQtyPick = function(variant_key) { if ($('#detail_qty[variant-key="' + variant_key + '"]').val() != undefined) { var e = parseInt($('#detail_qty[variant-key="' + variant_key + '"]').val().substr(7)); } return e; }; $scope.watchQty = function(variant_key) { var e = angular.element('select[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('select[name="detail_qty"][variant-key="' + variant_key + '"]'); } if ($('#detail_qty[variant-key="' + variant_key + '"]').val() != undefined) { $scope._data_qty_selected = parseInt($('#detail_qty[variant-key="' + variant_key + '"]').val().substr(7)); } console.log("_data_qty_selected", $scope._data_qty_selected); /* parseInt(e.val()); alert(i);onSelectVariantItems*/ if ($scope._data_qty_selected <= 0 || typeof $scope._data_qty_selected == 'undefined' || isNaN($scope._data_qty_selected)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } }; $scope.productQuantityMultiArray = []; $scope.lastCheckedVariantKey = ''; $scope.buildMultipleQuantity = function(productObj) { $scope.productQuantityMultiArray = []; var r = []; if (productObj.product_attribute.option_data != undefined && productObj.product_attribute.option_data.length > 0) { var p = productObj.product_attribute.option_data.variant_array; for (var i = 0; i < p.length; i++) { if (p[i].status == 1 && p[i].status == 1) { $scope.productQuantityMultiArray.push({ v_key: p[i].variant_key, v_name: p[i].option_name_array[0], v_qty: 1, v_active: 0 }); } } } }; $scope.switchQuantityByKey = function(variant_key) { $scope.lastCheckedVariantKey = variant_key; $('.d_qty').removeClass('active').removeClass('inin'); $('.d_qty_price[variant-key!="' + variant_key + '"]').removeClass('active').removeClass('inin'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('active'); $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('active'); $timeout(function() { $('.d_qty[variant-key="' + variant_key + '"]').addClass('inin'); $('.d_qty_price[variant-key="' + variant_key + '"]').addClass('inin'); }, 300); }; $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").find('select').val() != undefined) { check_int = parseInt($(".d_qty").find('select').val().substr(7)); } return check_int; }; $scope.warning = 0; $scope.getWarn = function() { $scope.warning = 1; }; $scope.outofstock = 0; $scope.getOutofstock = function() { $scope.outofstock = 1; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.onSelectVariantItems(0, ''); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { $scope.testyuyu = 0; if (option_id == '') { $scope.names = []; for (var i = 0; i < 20; i++) { $scope.names.push(i + 1); } $scope._dataArray.product_id = $scope._idUrl($scope._viewRouteParams().product_id); $scope._dataArray.product_price = $scope.data_min.price; $scope.testyuyu = 0; $('.d_qty_price').removeClass("active"); $('.d_qty_price').removeClass("inin"); $('.d_qty').removeClass('active').removeClass('inin'); $('.dsetting').addClass("active"); $('.d_qty_not_result').addClass("active"); $scope.dataVariantsPick[$index] = option_id; console.log("check_vareian 1000:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length); return GAEAPI.get('product/id', { 'txt_product_id': $scope._idUrl($routeParams.product_id) }).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; } }); } else { $scope.dataVariantsPick[$index] = option_id; for (var i = 0; i < $scope.dataVariantsPick.length; i++) { if ($scope.dataVariantsPick[i] != undefined && $scope.dataVariantsPick[i] != "") { $scope.testyuyu++; console.log("check_vareian 103", $scope.testyuyu); } } if ($scope.testyuyu >= $scope.dataOption.length) { console.log("check_vareian 104", $scope.testyuyu); $scope.testyuyu = 0; $scope.findVariantsData($scope.dataVariantsPick); $(".d_qty").find('select').val("number:1"); } else { console.log("check_vareian 105", $scope.testyuyu); $scope.testyuyu = 0; $(".d_qty").find('select').val("number:1"); } console.log("check_vareian 1001:", $scope.dataVariantsPick.length, $index, $scope.dataVariantsPick, $scope.dataOption.length, $scope.electric, $scope.testyuyu); } /*alert($scope.dataVariantsPick);*/ }; $scope.video_code = ""; $scope.videoShow = function() { $scope.video_code = $scope._dataArray.product_hightlight_video_embed; $(".videoHighlightOverlay").addClass("active"); console.log("videoShow"); } $scope.videoHide = function() { $scope.video_code = ''; $(".videoHighlightOverlay").removeClass("active"); console.log("videoHide"); } $scope.viewHide = function(arrayData, optionData) { var reTest = false; if (optionData == arrayData.length) { for (var i = 0; arrayData.length > i; i++) { console.log("arrayData[i]", arrayData[i]); if (!arrayData[i]) { reTest = false; break; } else { reTest = true; } } } return reTest; } $scope.viewHideOp = function(arrayData, optionData) { var e = false; if (optionData == 0 && arrayData.length == 0) { e = true; } return e; } $scope.qtuC = function() { var e = 1; if ($(".d_qty").find('select').val() == "") { $(".d_qty").find('select').val("number:1"); var e = 1; } else { var e = $(".d_qty").find('select').val(); } return e; } $scope.buyC = function() { var e = false; if ($scope.dataOption.length == 0 && $scope.viewHide($scope.dataVariantsPick, $scope.dataOption.length) == false) { if ($scope.names.length == 0) { e = false } else { e = true; } } else if ($scope.dataOption.length > 0) { if ($scope.viewHide($scope.dataVariantsPick, $scope.dataOption.length) == true) { if ($scope.stateShow == true) { e = true; } } else { e = false; } } return e; } $scope.outOfStockShow = function() { var e = false; if ($scope.buyC() == true) { e = true; } else { if ($scope.names.length == 20) { e = true; } else { e = false; } } return e; } }; return promise; });_ui_share_app.directive('componentProductDetails', function($rootScope, $routeParams, $location) { var templateComponent = 'componentProductDetails'; var templateUrl = _ui_share_host + templateComponent + '/' + templateComponent + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', type: '@type', cart: '@cart', buycol: '@buycol', buyicon: '@buyicon', buytext: '@buytext', viewcarttext: '@viewcarttext', buylogin: '@buylogin', currency: '@currency', checkstaff: '@checkstaff', language: '@language', btnstyle: '@btnstyle', maxstock: '@maxstock', videotext: '@videotext', description: '@description', info: '@info', sandwiched : '@sandwiched', specification: '@specification', textbrand:'@textbrand', navigationhover: '@navigationhover', imageappcoverchecked: '@imageappcoverchecked', categorylists:'@categorylists', categorylistsurl: '@categorylistsurl', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templateUrl; promise.transclude = { 'one': '?one', 'two': '?two', 'three': '?three', }; promise.controller = function($scope, $timeout, $interval, $window, $http, share) { $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._component = "componentProductDetails"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope._componentType = _ui_share_host + $scope._component + "/type/"; $scope._module = _ui_share_host + $scope._component + "/module/"; $scope._class = ($scope.type != undefined && $scope.type != "") ? $scope.type : "default"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._type = $scope._componentType + $scope._class + ".html"; $scope._cart = ($scope.cart != undefined && $scope.cart != "") ? $scope.cart : "trumpComponentCarts"; $scope._buycol = ($scope.buycol != undefined && $scope.buycol != "") ? parseInt($scope.buycol) : 15; $scope._maxstock = ($scope.maxstock != undefined && $scope.maxstock != "") ? parseInt($scope.maxstock) : 20; $scope._categorylistsurl = ($scope.categorylistsurl != undefined && $scope.categorylistsurl != "") ? $scope.categorylistsurl : "category-lists"; $scope._btnstyle = ($scope.btnstyle != undefined && $scope.btnstyle != "") ? $scope.btnstyle : "filled_button_large"; $scope._buylogin = ($scope.buylogin == "true" || $scope.buylogin == "t") ? true : false; $scope._checkstaff = ($scope.checkstaff == "true" || $scope.checkstaff == "t") ? true : false; $scope._categorylists = ($scope.categorylists != undefined && $scope.categorylists != "") ? $scope.categorylists : "สินค้า"; $scope._sandwiched = ($scope.sandwiched != undefined && $scope.sandwiched != "") ? $scope.sandwiched : ">"; $scope._currency = ($scope.currency != undefined && $scope.currency != "") ? $scope.currency : "THB"; $scope._buyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope.buyicon : "icnt_outline_cart01_dark.png"; $scope._buytext = ($scope.buytext != undefined && $scope.buytext != "") ? $scope.buytext : "เพิ่มในรถเข็น"; $scope._viewcarttext = ($scope.viewcarttext != undefined && $scope.viewcarttext != "") ? $scope.viewcarttext : "ดูรถเข็น"; $scope._videotext = ($scope.videotext != undefined && $scope.videotext != "") ? $scope.videotext : "Video"; $scope._icebuyicon = ($scope.buyicon != undefined && $scope.buyicon != "") ? $scope._icnPath + $scope.buyicon : $scope._icnPath + "icnt_outline_cart01_dark.png"; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; $scope._textbrand = ($scope.textbrand != undefined && $scope.textbrand != "") ? $scope.textbrand : "Brand"; $scope._navigationhover = ($scope.navigationhover != undefined && $scope.navigationhover != "") ? $scope.navigationhover : "primary"; $scope._imageappcoverchecked = ($scope.imageappcoverchecked == "true" || $scope.imageappcoverchecked == "t") ? true : false; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getNamePage: function(arr) { var str = []; for (var i = 0; i < arr.length; i++) { if (i != 0) { str.push(arr[i]); } } return str.join(" "); }, getProductId: function(params, callback) { var _self = this; var product_id = (params.product_id != undefined) ? params.product_id.split("-", 1).join("") : false; _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getReferralId: function(productReferralDisplay, callback) { var _self = this; var referral_id = 0; if (productReferralDisplay.length != 0) { if (productReferralDisplay.category != undefined) { if (productReferralDisplay.category.length != 0) { referral_id = productReferralDisplay.category[0].referral_id } } } callback(referral_id); }, getStaffId: function(staffId, callback) { var _self = this; var res_staff = { staff_id: (staffId != 0 && staffId != '' && staffId != undefined) ? staffId : '0', status: (staffId != 0 && staffId != '' && staffId != undefined) ? true : false } callback(res_staff); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carouselA: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ fade: true, dots: false, arrows: false, infinite: true, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselB: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: true, arrows: true, infinite: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselD: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: false, arrows: true, infinite: true, autoplay: true, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, prevArrow: '', nextArrow: '', speed: 600, }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselBar: function(cover, carousel) { var _self = this; $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); setTimeout(function() { var carousels = $(carousel); carousels.not('.slick-initialized').slick({ dots: false, arrows: false, infinite: false, autoplay: false, adaptiveHeight: true, autoplaySpeed: 4000, slidesToShow: 6, slidesToScroll: 6, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 5, slidesToScroll: 5, } }, { breakpoint: 991, settings: { slidesToShow: 4, slidesToScroll: 4, } }, { breakpoint: 767, settings: { slidesToShow: 3, slidesToScroll: 3, } }] }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, slickCarousel: function(carousel, index) { var _self = this; $scope.setCarousel.index = index; setTimeout(function() { $('[data-key="' + carousel + '"]').slick('slickGoTo', index); }, 100); }, prevIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != 0) ? image_index - 1 : image - 1; _self.consoleLog("prevIndex index", $scope.setCarousel.index); }, nextIndex: function(product_image) { var _self = this; var image = product_image.length; var image_index = $scope.setCarousel.index; $scope.setCarousel.index = (image_index != (image - 1)) ? image_index + 1 : 0; _self.consoleLog("nextIndex index", $scope.setCarousel.index); } } return getFunction; }; $scope.getAttribute = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, productAttribute: function(productAttribute, callback) { var _self = this; var attribute = { option_name: "", option_attribute: [] }; if (productAttribute.option_data != undefined) { if (productAttribute.option_data.variant_array != undefined && productAttribute.option_data.variant_array.length != 0) { for (var a = 0; a < productAttribute.option_data.pclass_array.length; a++) { attribute.option_name = attribute.option_name.concat(productAttribute.option_data.pclass_array[a].pclass_name, " "); } for (var b = 0; b < productAttribute.option_data.variant_array.length; b++) { var product_attribute = { product_id: productAttribute.option_data.variant_array[b].product_id, product_sku: productAttribute.option_data.variant_array[b].sku, product_title: "", product_price: parseFloat(productAttribute.option_data.variant_array[b].price), product_compare_price: parseFloat(productAttribute.option_data.variant_array[b].compare_price), product_total_stock: parseFloat(productAttribute.option_data.variant_array[b].total_stock), product_image: productAttribute.option_data.variant_array[b].variant_image } for (var c = 0; c < productAttribute.option_data.variant_array[b].option_name_array.length; c++) { product_attribute.product_title = product_attribute.product_title.concat(productAttribute.option_data.variant_array[b].option_name_array[c], " "); } attribute.option_attribute.push(product_attribute); } } } _self.consoleLog("productAttribute attribute ", attribute); callback(attribute); }, checkDiscountPrice: function(productDiscount, resPrice, resComparePrice, callback) { var _self = this; var price = 0; var compare_price = 0; if (productDiscount.length == 0) { price = parseFloat(resPrice); compare_price = parseFloat(resComparePrice); } else { if (productDiscount.discount_type_id == '101') { price = parseFloat(resPrice) - parseFloat(productDiscount.discount_price); compare_price = parseFloat(resPrice); } else if (productDiscount.discount_type_id == '102') { price = (parseFloat(resPrice) * ((100 - parseFloat(productDiscount.discount_percent)) / 100)); compare_price = parseFloat(resPrice); } } callback(price, compare_price); }, checkMinPrice: function(option, callback) { var _self = this; var price_min = parseFloat(option.option_attribute[0].product_price); var compare_price_min = parseFloat(option.option_attribute[0].product_compare_price); var total_stock = parseFloat(option.option_attribute[0].product_total_stock); for (var a = 0; a < option.option_attribute.length; a++) { if (price_min >= parseFloat(option.option_attribute[a].product_price)) { price_min = parseFloat(option.option_attribute[a].product_price); compare_price_min = parseFloat(option.option_attribute[a].product_compare_price); total_stock = parseFloat(option.option_attribute[a].product_total_stock); } } _self.consoleLog("checkPriceMin price_min ", price_min); _self.consoleLog("checkPriceMin compare_price_min ", compare_price_min); _self.consoleLog("checkPriceMin total_stock ", total_stock); callback(price_min, compare_price_min, total_stock); }, getTotalStock: function(totalStock, mixStock, callback) { var _self = this; var total_stock = (totalStock > 0) ? ((totalStock <= mixStock) ? totalStock : mixStock) : ((totalStock == -1) ? mixStock : totalStock); callback(total_stock); }, checkMinPrices: function(api, attribute, callback) { var _self = this; var dataPrice = { product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 } } if (attribute.option_attribute.length == 0) { _self.checkDiscountPrice(api.data.product_discount, api.data.product_price, api.data.product_compare_price, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(api.data.product_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, false); }); }); }); }); }); } else { _self.checkMinPrice(attribute, function(res_price_min, res_compare_price_min, res_total_stock) { _self.checkDiscountPrice(api.data.product_discount, res_price_min, res_compare_price_min, function(res_price, res_compare_price) { _self.checkPrice(res_price, function(res_price_ecimals) { dataPrice.product_price.price = res_price; dataPrice.product_price.price_ecimals = res_price_ecimals; dataPrice.sum_product_price.price = res_price; dataPrice.sum_product_price.price_ecimals = res_price_ecimals; _self.checkPrice(res_compare_price, function(res_compare_price_ecimals) { dataPrice.product_compare_price.price = res_compare_price; dataPrice.product_compare_price.price_ecimals = res_compare_price_ecimals; dataPrice.sum_product_compare_price.price = res_compare_price; dataPrice.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((res_compare_price - res_price) > 0) ? res_compare_price - res_price : 0; _self.checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { dataPrice.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; dataPrice.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.getTotalStock(res_total_stock, $scope._maxstock, function(res_total_stock_s) { dataPrice.product_price.total_stock = res_total_stock_s; dataPrice.product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_price.total_stock = res_total_stock_s; dataPrice.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; callback(dataPrice, true); }); }); }); }); }); }); } }, priceIncludes: function(price, includes, callback) { var _self = this; var priceToString = (price == null) ? 0 : price; _self.consoleLog('priceIncludes priceToString : ', priceToString); callback(priceToString.toString().includes(includes)); }, checkPrice: function(price, callback) { var _self = this; _self.priceIncludes(price, '.', function(res) { _self.consoleLog("checkPrice res ", res); callback((!res) ? 0 : 2); }); }, onSelectOption: function(productId) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = productId; _self.consoleLog("onSelectOption productId ", productId); $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); for (var a = 0; a < $scope.data.attribute.dataArray.option_attribute.length; a++) { _self.consoleLog("onSelectOption option_attribute ", $scope.data.attribute.dataArray.option_attribute[a]); if ($scope.data.attribute.dataArray.option_attribute[a].product_id == productId) { if ($scope.data.attribute.dataArray.option_attribute[a].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var b = 0; b < $scope.dataApi.product.dataArray.product_image.length; b++) { if ($scope.dataApi.product.dataArray.product_image[b].image_id == $scope.data.attribute.dataArray.option_attribute[a].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, b); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[a].product_price, $scope.data.attribute.dataArray.option_attribute[a].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[a].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); break; } } }, onClickOption: function(index) { var _self = this; $scope.data.quantity.quantity_input = 1; $scope.dataApi.product.dataArray.product_id = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.data.attribute.productId = $scope.data.attribute.dataArray.option_attribute[index].product_id; $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); if ($scope.data.attribute.dataArray.option_attribute[index].product_image.length != 0) { if ($scope.dataApi.product.dataArray.product_image.length != 0) { for (var i = 0; i < $scope.dataApi.product.dataArray.product_image.length; i++) { if ($scope.dataApi.product.dataArray.product_image[i].image_id == $scope.data.attribute.dataArray.option_attribute[index].product_image[0].image_id) { $scope.getCarousel().slickCarousel($scope.setCarousel.carousel, i); } } } } _self.checkDiscountPrice($scope.dataApi.product.dataArray.product_discount, $scope.data.attribute.dataArray.option_attribute[index].product_price, $scope.data.attribute.dataArray.option_attribute[index].product_compare_price, function(res_price_p, res_compare_price_p) { _self.checkPrice(res_price_p, function(res_price_ecimals_p) { $scope.data.product_price.price = res_price_p; $scope.data.product_price.price_ecimals = res_price_ecimals_p; $scope.data.sum_product_price.price = res_price_p; $scope.data.sum_product_price.price_ecimals = res_price_ecimals_p; _self.checkPrice(res_compare_price_p, function(res_compare_price_ecimals_p) { $scope.data.product_compare_price.price = res_compare_price_p; $scope.data.product_compare_price.price_ecimals = res_compare_price_ecimals_p; $scope.data.sum_product_compare_price.price = res_compare_price_p; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals_p; var compare_price_minus_price_p = ((res_compare_price_p - res_price_p) > 0) ? res_compare_price_p - res_price_p : 0; _self.checkPrice(compare_price_minus_price_p, function(res_compare_price_minus_price_ecimals_p) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price_p; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals_p; _self.getTotalStock($scope.data.attribute.dataArray.option_attribute[index].product_total_stock, $scope._maxstock, function(res_total_stock_s) { $scope.data.product_price.total_stock = res_total_stock_s; $scope.data.product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_price.total_stock = res_total_stock_s; $scope.data.sum_product_compare_minus_sum_product_price.total_stock = res_total_stock_s; /* stock */ $scope.data.quantity.quantity_max = res_total_stock_s; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_total_stock_s; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* stock */ }) }); }); }); }); } } return getFunction; }; $scope.getAttributeCustom = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, createArray: function(productCustomTemplates, callback) { var _self = this; var custom_attributes = []; if (productCustomTemplates.templates.length != 0) { angular.forEach(productCustomTemplates.templates, function(item, index) { if (item.option_sets.length != 0) { _self.getAttributes(item.option_sets, function(res_attributes) { custom_attributes = custom_attributes.concat(res_attributes); }); } }); /* if (productCustomTemplates.templates[0].option_sets.length != 0) { _self.getAttributes(productCustomTemplates.templates[0].option_sets, function(res_attributes) { custom_attributes = res_attributes; }); } */ } _self.consoleLog("createArray : productCustomTemplates", productCustomTemplates); _self.consoleLog("createArray : custom_attributes", custom_attributes); callback(custom_attributes, true); }, formatAttribute: function(index, optionSubsetIndex, setType, optionSetArray, callback) { var _self = this; var set_id = (setType == 'attribute') ? optionSetArray.set_id : optionSetArray.subset_id; var attribute = { attribute_index: index, attribute_option_subset_index: optionSubsetIndex, active_option_id: (optionSetArray.option_data.select_id != 0) ? optionSetArray.option_data.select_id : "-1", active_option_index: -1, active_option_index_str: "-1", active_textarea: "", active_array: [], set_id: set_id, name: optionSetArray.name, set_type: optionSetArray.ss_type, option: [] } callback(attribute); }, getOption: function(index, optionDataArray, callback) { var _self = this; var options = { index: index, ss_data_id: optionDataArray.ss_data_id, name: optionDataArray.name, image: optionDataArray.image, price: optionDataArray.price, compare_price: 0, total_stock: 0 } callback(options); }, getActive: function(index, activeOptionId, activeOptionIdIn, optionDataArray, callback) { var _self = this; var actives_index = (optionDataArray.ss_data_id == activeOptionId) ? index : activeOptionIdIn; var actives = (optionDataArray.ss_data_id != activeOptionId) ? "0" : "1"; callback(actives_index, actives); }, getAttributes: function(optionSetArray, callback) { var _self = this; var attributes = []; for (var index = 0; index < optionSetArray.length; index++) { _self.formatAttribute(index, 0, 'attribute', optionSetArray[index], function(res_attribute) { if (optionSetArray[index].option_subsets.length != 0) { for (var option_subset_index = 0; option_subset_index < optionSetArray[index].option_subsets.length; option_subset_index++) { _self.formatAttribute(index, option_subset_index, res_attribute.set_type, optionSetArray[index].option_subsets[option_subset_index], function(res_attribute_sub) { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_subsets[option_subset_index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute_sub.active_option_id, active_option_id, optionSetArray[index].option_subsets[option_subset_index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute_sub.option = options; res_attribute_sub.active_option_index = active_option_id; res_attribute_sub.active_option_index_str = String(active_option_id); res_attribute_sub.active_array = active_option_array; attributes.push(res_attribute_sub); }); } } else { var options = []; var active_option_id = -1; var active_option_array = []; for (var option = 0; option < optionSetArray[index].option_data.options.length; option++) { _self.getOption(option, optionSetArray[index].option_data.options[option], function(res_option) { options.push(res_option); }); _self.getActive(option, res_attribute.active_option_id, active_option_id, optionSetArray[index].option_data.options[option], function(res_actives_index, res_actives) { active_option_id = res_actives_index; active_option_array.push(res_actives); }); } res_attribute.option = options; res_attribute.active_option_index = active_option_id; res_attribute.active_option_index_str = String(active_option_id); res_attribute.active_array = active_option_array; attributes.push(res_attribute); } }); } callback(attributes) }, getformatQuantity: function(index, attributeCustom, callback) { var _self = this; var quantity = { name: String(index + 1), dataArray: attributeCustom } callback(quantity); }, onClickRadio: function(index, index_option) { var _self = this; _self.consoleLog("onClickRadio : index", index); _self.consoleLog("onClickRadio : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickRadio : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickDropdown: function(index, index_option) { var _self = this; _self.consoleLog("onClickDropdown : index", index); _self.consoleLog("onClickDropdown : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i != parseInt(index_option)) ? "0" : "1"; } _self.consoleLog("onClickDropdown : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); }, onClickCheckbox: function(index, index_option) { var _self = this; _self.consoleLog("onClickCheckbox : index", index); _self.consoleLog("onClickCheckbox : index_option", index_option); $scope.data.attribute_custom.dataArray[index].active_option_index = parseInt(index_option); $scope.data.attribute_custom.dataArray[index].active_option_index_str = String(index_option); for (var i = 0; i < $scope.data.attribute_custom.dataArray[index].active_array.length; i++) { $scope.data.attribute_custom.dataArray[index].active_option_id = (i != parseInt(index_option)) ? $scope.data.attribute_custom.dataArray[index].active_option_id : $scope.data.attribute_custom.dataArray[index].option[i].ss_data_id; $scope.data.attribute_custom.dataArray[index].active_array[i] = (i == parseInt(index_option)) ? (($scope.data.attribute_custom.dataArray[index].active_array[i] != "0") ? "0" : "1") : $scope.data.attribute_custom.dataArray[index].active_array[i]; } _self.consoleLog("onClickCheckbox : $scope.data.attribute_custom.dataArray[index]", $scope.data.attribute_custom.dataArray[index]); } } return getFunction; }; $scope.getReward = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, momentUnix: function(callback) { var _self = this; var now = moment().unix(); callback(now); }, getCalculator: function(sumProductPrice, reward, callback) { var _self = this; _self.consoleLog("getCalculator : sumProductPrice", sumProductPrice); _self.consoleLog("getCalculator : reward", reward); var point_reward = 0; if (reward.type_id == "100") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } else if (reward.type_id == "101") { point_reward = reward.reward_amount; } else if (reward.type_id == "102") { point_reward = (reward.reward_percent * sumProductPrice.price) / 100; } else if (reward.type_id == "103") { point_reward = Math.floor((sumProductPrice.price / reward.reward_every_price)) * reward.reward_amount; } _self.consoleLog("getCalculator : point_reward", point_reward); callback(point_reward); }, getProductReward: function(now, productReward, callback) { var _self = this; var reward = { reward_length: (productReward.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(productReward.reward_lifetime.lifetime_start_time); reward.lifetime_end_time = parseInt(productReward.reward_lifetime.lifetime_end_time); reward.type_id = productReward.reward_type_id; reward.amount = parseInt(productReward.reward_amount); reward.percent = parseInt(productReward.reward_percent); reward.every_price = parseInt(productReward.reward_every_price); } _self.consoleLog("getProductReward : reward", reward); callback(reward); }, getPointConfig: function(now, shopPointConfig, callback) { var _self = this; var reward = { reward_length: (shopPointConfig.length != 0) ? true : false, lifetime_time: 0, lifetime_start_time: 0, lifetime_end_time: 0, type_id: "0", amount: 0, percent: 0, every_price: 0 }; reward.lifetime_time = now; if (reward.reward_length) { reward.lifetime_start_time = parseInt(shopPointConfig.er_from); reward.lifetime_end_time = parseInt(shopPointConfig.er_to); reward.type_id = "100"; reward.amount = parseInt(shopPointConfig.er_earn); reward.every_price = parseInt(shopPointConfig.er_rate); } _self.consoleLog("getPointConfig : reward", reward); callback(reward); }, checkPointReward: function(reward, callback) { var _self = this; var state = false; if (reward.reward_length) { var start = reward.lifetime_start_time < reward.lifetime_time && reward.lifetime_start_time != 0; var end = (reward.lifetime_end_time != -1) ? reward.lifetime_time <= reward.lifetime_end_time && reward.lifetime_end_time != 0 : true; if (start && end) { if (reward.type_id == "100") { var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } else if (reward.type_id == "101") { var amount = reward.amount != 0; if (amount) { state = true; } } else if (reward.type_id == "102") { var percent = reward.percent != 0; if (percent) { state = true; } } else if (reward.type_id == "103") { var percent = reward.percent != 0; var amount = reward.amount != 0; var every_price = reward.every_price != 0; if (amount && every_price) { state = true; } } } } callback(state); }, checkReward: function(rewardProduct, rewardPointConfig, callback) { var _self = this; _self.consoleLog("checkReward : rewardProduct", rewardProduct); _self.consoleLog("checkReward : rewardPointConfig", rewardPointConfig); var reward = { type_id: "0", amount: 0, percent: 0, every_price: 0 }; _self.checkPointReward(rewardProduct, function(res_state_product) { _self.checkPointReward(rewardPointConfig, function(res_state_point_config) { if (res_state_point_config) { reward.type_id = rewardPointConfig.type_id; reward.type_id = rewardPointConfig.type_id; reward.amount = rewardPointConfig.amount; reward.percent = rewardPointConfig.percent; reward.every_price = rewardPointConfig.every_price; } else if (res_state_product) { reward.type_id = rewardProduct.type_id; reward.amount = rewardProduct.amount; reward.percent = rewardProduct.percent; reward.every_price = rewardProduct.every_price; } _self.consoleLog("checkReward : reward", reward); callback(reward); }); }); }, checkRewardType: function(productReward, shopPointConfig, callback) { var _self = this; _self.momentUnix(function(now) { _self.getProductReward(now, productReward, function(res_reward_product) { _self.getPointConfig(now, shopPointConfig, function(res_reward_point_config) { _self.checkReward(res_reward_product, res_reward_point_config, function(res_reward) { callback(res_reward); }); }); }); }); }, createReward: function(productReward, shopPointConfig, callback) { var _self = this; _self.consoleLog("createReward : productReward", productReward); _self.consoleLog("createReward : shopPointConfig", shopPointConfig); _self.checkRewardType(productReward, shopPointConfig, function(res_reward) { _self.consoleLog("createReward : res_reward", res_reward); callback(res_reward); }); } } return getFunction; }; $scope.getQuantity = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, upDateReward: function() { var _self = this; }, upDateReward: function() { var _self = this; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); }, upDatePrice: function() { var _self = this; var product_price = $scope.data.product_price.price * $scope.data.quantity.quantity_input; var product_compare_price = $scope.data.product_compare_price.price * $scope.data.quantity.quantity_input; $scope.getAttribute().checkPrice(product_price, function(res_price_ecimals) { $scope.data.sum_product_price.price = product_price; $scope.data.sum_product_price.price_ecimals = res_price_ecimals; $scope.getAttribute().checkPrice(product_compare_price, function(res_compare_price_ecimals) { $scope.data.sum_product_compare_price.price = product_compare_price; $scope.data.sum_product_compare_price.price_ecimals = res_compare_price_ecimals; var compare_price_minus_price = ((product_compare_price - product_price) > 0) ? product_compare_price - product_price : 0; $scope.getAttribute().checkPrice(compare_price_minus_price, function(res_compare_price_minus_price_ecimals) { $scope.data.sum_product_compare_minus_sum_product_price.price = compare_price_minus_price; $scope.data.sum_product_compare_minus_sum_product_price.price_ecimals = res_compare_price_minus_price_ecimals; _self.upDateReward(); }); }); }); }, input: function(quantityInput) { var _self = this; quantityInput = (quantityInput == null) ? 1 : parseInt(quantityInput); _self.consoleLog("input : quantityInput", quantityInput); if (quantityInput != null) { if (quantityInput >= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_max; } if (quantityInput <= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } } else { $scope.data.quantity.quantity_input = $scope.data.quantity.quantity_min; } _self.upDatePrice(); }, minus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input - 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_min", $scope.data.quantity.quantity_min); if (quantity >= $scope.data.quantity.quantity_min) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); }, plus: function() { var _self = this; var quantity = $scope.data.quantity.quantity_input + 1; _self.consoleLog("plus : quantity", quantity); _self.consoleLog("plus : quantity_max", $scope.data.quantity.quantity_max); if (quantity <= $scope.data.quantity.quantity_max) { $scope.data.quantity.quantity_input = quantity; } _self.upDatePrice(); } } return getFunction; }; $scope.getBuy = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getProductId: function(params, callback) { var _self = this; var product_id = params.product_id.split("-", 1).join(""); _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, postApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.post(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, UiCartProductAdd: function(productId, quantityInput, promotionId, customOptions, callback) { quantityInput = (quantityInput > $scope.data.quantity.quantity_max) ? $scope.data.quantity.quantity_max : quantityInput; UiCart.delegate.product.add(productId, quantityInput, promotionId, function(res_data) { callback(res_data); }); }, isLogin: function(callback) { var buy_login = $scope._buylogin; var is_login = UiCustomerBox.delegate.get.isLogin(); var is_state = (buy_login) ? (!is_login) ? true : false : false; callback(is_state); }, formLogin: function(is_state, callback) { if (is_state) { $inloginPopup.open(); } callback(is_state); }, getProductStaffId(staff_id_check, callback) { var res_staff_id_check = staff_id_check; var res_staff_id = $scope.dataApi.product.dataArray.product_staff_id; var res_is_state = (res_staff_id != 0 && res_staff_id != '0' && res_staff_id != undefined) ? true : false; callback(res_staff_id_check, res_staff_id, res_is_state); }, isStaffId: function(staff_id_check, callback) { /* todo */ var _self = this; _self.getProductStaffId(staff_id_check, function(res_staff_id_check, res_staff_id, res_is_state) { callback(res_staff_id_check, res_staff_id, res_is_state); }); }, checkCartDuplicateStaff: function(res_staff_id_check, txt_staff_id, res_is_state, callback) { var _self = this var res_is_state = true; if (res_staff_id_check) { var dataSend = { 'txt_staff_id': txt_staff_id, }; _self.dataSend("cart/duplicate_staff", dataSend, function(res_api, res_dataSend) { _self.postApi(res_api, res_dataSend, function(res_ok, res_api, state) { res_is_state = res_api.data.duplicate; callback(res_is_state); }); }); } else { callback(res_is_state); } }, showAlert: function(res_staff_id_check, res_staff_id, res_is_state, res_api, callback) { var res_state = (res_staff_id_check) ? ((res_api) ? ((res_is_state) ? false : true) : true) : false; if (res_state) { if (!res_api) { if (res_staff_id != '0' && res_staff_id != 0) { $scope.controlAlert().alert('002'); } else { $scope.controlAlert().alert('003'); } } else { if (!res_is_state) { $scope.controlAlert().alert('003'); } } } callback(res_state); }, checkStaff: function(callback) { var _self = this var staff_id_check = $scope._checkstaff; var res_check = false; _self.isStaffId(staff_id_check, function(res_staff_id_check, res_staff_id, res_is_state) { _self.checkCartDuplicateStaff(res_staff_id_check, res_staff_id, res_is_state, function(res_api) { _self.showAlert(res_staff_id_check, res_staff_id, res_is_state, res_api, function(res_state) { res_check = res_state; callback(res_check); }); }); }); }, isProgress: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isProgress(productId)) ? true : false; _self.consoleLog("isProgress : productId", productId); _self.consoleLog("isProgress : state", state); callback(state); }, isSelected: function(productId, callback) { var _self = this; var state = (UiCart.delegate.product.isSelected(productId)) ? true : false; _self.consoleLog("isSelected : productId", productId); _self.consoleLog("isSelected : state", state); callback(state); }, isSelectedReturn: function(productId) { var _self = this; var ui_cart_state = (UiCart.delegate.product.isSelected(productId)) ? true : false; if (!$scope.setBuy.state_active) { $scope.setBuy.state_active = true; var state_process = $scope.setBuy.state_process; var state_step = $scope.setBuy.state_step; if (ui_cart_state && !state_process && state_step != 4) /* cart */ { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else if (!ui_cart_state && !state_process && state_step != 0) /* unset */ { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_active = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } else { $scope.setBuy.state_active = false; } } return ui_cart_state; }, updateState: function(productId) { _self = this; _self.isSelected(productId, function(res_state) { if (res_state) { _self.onTimeout(250, function() { _self.onPass(1, function(res_step) { _self.onTimeout(500, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onUnset(0, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); } return res_state; }); }, uiCart: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; _self.UiCartProductAdd(productId, quantityInput, promotionId, customOptions, function(res_data) { if (res_data) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; if ($scope._cart == "trumpComponentCarts") { _self.trumpComponentCarts(); } }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }, postApiA: function(productId, quantityInput, promotionId, customOptions, res_step) { var _self = this; var custom_options = {}; var dataSend = { 'txt_product_id': productId, 'txt_amount': quantityInput, 'txt_is_clear_cart_before': "0", 'txt_custom_options_json': JSON.stringify(custom_options) }; _self.dataSend("cart/product_add", dataSend, function(res_api, res_dataSend) { _self.postApi(res_api, res_dataSend, function(res_ok, res_api, state) { if (res_ok) { _self.onTimeout(500, function() { _self.onPass(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onCart(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[4].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[4].data_background_color; }); }); }); }); } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); }); }, onProcess: function(data, productId, quantityInput, promotionId, customOptions) { var _self = this; _self.isLogin(function(res_is_login) { _self.formLogin(res_is_login, function(res_form) { _self.checkStaff(function(res_is_state) { if (!$scope.setBuy.state_process && !res_form && !res_is_state) { $scope.setBuy.state_process = true; _self.isSelected(productId, function(res_state) { if (!res_state) { _self.onLoad($scope.setBuy.state_step, function(res_step) { if (data.sum_product_price.price != 0 && data.quantity.quantity_max != 0 && (data.attribute.state == (data.attribute.productId != ''))) { /* UiCart */ _self.uiCart(productId, quantityInput, promotionId, customOptions, res_step); /* api post offline */ /*_self.postApiA(productId, quantityInput, promotionId, customOptions, res_step); */ } else { _self.onTimeout(500, function() { _self.onError(res_step, function(res_step) { _self.onTimeout(1000, function() { _self.onUnset(res_step, function(res_step) { $scope.setBuy.state_process = false; $scope.setBuy.state_data_font_color = $scope.setBuy.stepArray[0].data_font_color; $scope.setBuy.state_data_background_color = $scope.setBuy.stepArray[0].data_background_color; }); }); }); }); } }); } else { $scope.setBuy.state_process = false; if ($scope._cart == "trumpComponentCarts") { _self.trumpComponentCarts(); } else if ($scope._cart == "viewcart") { _self.viewCart($scope._cart); } } }); } }); }); }); }, onTimeout: function(time, callback) { var _self = this; var load = $timeout(function() { $timeout.cancel(load); callback(true) }, time); }, onUnset: function(step, callback) { var _self = this; step = (step == 0) ? 0 : 0; $scope.setBuy.state_step = step; callback(step); }, onLoad: function(step, callback) { var _self = this; step = (step == 0 || step == 1) ? 1 : 0; $scope.setBuy.state_step = step; callback(step); }, onPass: function(step, callback) { var _self = this; step = (step == 1 || step == 2) ? 2 : 0; $scope.setBuy.state_step = step; callback(step); }, onError: function(step, callback) { var _self = this; step = (step == 1 || step == 3) ? 3 : 0; $scope.setBuy.state_step = step; callback(step); }, onCart: function(step, callback) { var _self = this; step = (step == 2 || step == 4) ? 4 : 0; $scope.setBuy.state_step = step; callback(step); }, trumpComponentCarts: function() { var controlCart = share.getTrumpComponentCarts(); var component_carts = $('.cover-cards').hasClass('active'); if (!component_carts) { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.cart(); } } else { var component_icon_cart = $("div").hasClass('cover-icon-carts'); if (component_icon_cart) { controlCart.load(); } } }, viewCart: function(viewcart) { var _self = this; _self.pageUrl(viewcart); }, locationUrlReplace: function(page) { $location.url(page).replace(); }, pageUrl: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page); }, main: function(callback) { var _self = this; } } return getFunction; }; $scope.getDetail = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getDetail: function(api, callback) { var _self = this; var description = api.product_description; var info = api.product_more_info; var specificatio = []; if (api.product_attribute.specification_data != undefined) { specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? api.product_attribute.specification_data.pclass_array : []; } var state_specificatio = false; if (api.product_attribute.specification_data != undefined) { state_specificatio = (api.product_attribute.specification_data.length != 0 && api.product_attribute.specification_data != undefined) ? true : false; } var state_info = (api.product_is_more_info == 1) ? true : false; _self.consoleLog("getDetail : description", description); _self.consoleLog("getDetail : info", info); _self.consoleLog("getDetail : state_info", state_info); _self.consoleLog("getDetail : specificatio", specificatio); _self.consoleLog("getDetail : state_specificatio", state_specificatio); callback(description, info, state_info, specificatio, state_specificatio); }, onClickDetail: function(index) { var _self = this; $scope.data.detail.active = index; _self.consoleLog("onClickDetail : data.detail.active", $scope.data.detail.active); } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageName: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page_name); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.countDown = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getLocation: function(callback) { var _self = this; var res_location = $location; _self.consoleLog("getLocation", "res_location", res_location); callback(res_location); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; _self.consoleLog("getRouteParams", "params", params); callback(params); }, getLocationUrlNameProductDetail: function(callback) { var _self = this; _self.getRouteParams(function(res_params) { _self.getLocation(function(res_location) { var url_page_name = "/product-detail/" + res_params.product_id; var res_url_name_product_detail = (res_location.url() == url_page_name) ? true : false; _self.consoleLog("getLocationUrlNameProductDeal", "res_url_name_product_detail", res_url_name_product_detail); callback(res_url_name_product_detail); }); }); }, getUnix: function(callback) { var _self = this; var now = moment().unix(); _self.consoleLog("getUnix", "now", now); callback(now); }, getCountDown: function(now, product_lifetime, callback) { var _self = this; var countdown_unix = parseInt(product_lifetime.lifetime_end_time) - now; var milliseconds = moment.duration(countdown_unix * 1000, "milliseconds"); var res_countdown = ((milliseconds.days() <= 9) ? '0' + milliseconds.days() : milliseconds.days()); res_countdown = res_countdown + ' : ' + ((milliseconds.hours() <= 9) ? '0' + milliseconds.hours() : milliseconds.hours()); res_countdown = res_countdown + ' : ' + ((milliseconds.minutes() <= 9) ? '0' + milliseconds.minutes() : milliseconds.minutes()); res_countdown = res_countdown + ' : ' + ((milliseconds.seconds() <= 9) ? '0' + milliseconds.seconds() : milliseconds.seconds()); _self.consoleLog("getCountDown", "res_countdown", res_countdown); callback(res_countdown, countdown_unix); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name) { var _self = this; var page = page_name; _self.locationUrlReplace(page); }, countDownByProduct: function(now, data_array, callback) { var _self = this; if (data_array.length != 0) { if (data_array.product_lifetime.length != 0) { _self.getCountDown(now, data_array.product_lifetime, function(res_count_down, res_countdown_unix) { data_array.product_lifetime.lifetime_countdown = (res_countdown_unix > 0) ? res_count_down : ""; if (data_array.product_lifetime.lifetime_countdown == "") { _self.getNameUrl(data_array.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", data_array.product_set_array[0].product_id, res_name); }); } }); } } _self.consoleLog("countDownByProduct", "data_array", data_array); callback(data_array); }, loop: function() { var _self = this; var load = $timeout(function() { $timeout.cancel(load); _self.getUnix(function(res_now) { _self.countDownByProduct(res_now, $scope.dataApi.product.dataArray, function(data_array) { $scope.dataApi.product.dataArray = data_array; _self.getLocationUrlNameProductDetail(function(res_url_name_product_detail) { if (res_url_name_product_detail) { _self.loop(); } }); }); }); }, 1000); } } return getFunction; }; $scope.getPromotion = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, setPromotionId: function(promotion_id) { var _self = this; _self.consoleLog("setPromotionId", "promotion_id", promotion_id); $scope.data.promotion.promotion_id = promotion_id; _self.consoleLog("setPromotionId", "data.promotion.promotion_id", $scope.data.promotion.promotion_id); }, } return getFunction; }; $scope.control = function() { var getFunction = { popupVideo: function(state, video_link, video_embed_code) { var _self = this; if (video_embed_code != '') { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } else if (video_link != '') { window.open(video_link, '_blank'); } else { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } }, main: function() { var _self = this; } } return getFunction; }; $scope.data_control = { page_video: { popup: false, shop_video_embed_code: "" } } $scope.control_alert = { alert: { error_id: '', index: null, state: true, error: [{ id: '001', title: 'การสั่งซื้อ', messages: 'สามารถสั่งซื้อได้เพียงทีละออเดอร์เท่านั้น' }, { id: '002', title: 'การเพิ่มสินค้า', messages: 'ไม่สามารถเพิ่มสินค้าของร้านมากกว่า 1 ร้านค้าได้' }, { id: '003', title: 'การสั่งซื้อ', messages: 'ไม่สามารถเพิ่มสินค้า(ไม่มีร้านค้า)' }] } }; $scope.controlAlert = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getErrorMessages: function(error_id, callback) { var _self = this; var messages = { res_error_id: '', res_index: null } angular.forEach($scope.control_alert.alert.error, function(item, index) { if (item.id == error_id) { messages.res_error_id = item.id; messages.res_index = index; } }); callback(messages.res_error_id, messages.res_index); }, alert: function(error_id) { var _self = this; _self.getErrorMessages(error_id, function(res_error_id, res_index) { $scope.control_alert.alert.error_id = res_error_id; $scope.control_alert.alert.index = res_index; $scope.control_alert.alert.state = (!$scope.control.alert && res_error_id != '') ? true : false; }); }, main: function() { var _self = this; } } return getFunction; }; $scope.countDown().loop(); /* set carousel */ $scope.setCarousel = { carousel: 0, index: 0 }; $scope.getCarousel().getCarousel($scope.setCarousel.carousel, function(res_carousel_id) { $scope.setCarousel.carousel = res_carousel_id; }); /* set carousel */ /* get product api */ $scope.dataApi = { reward: { dataSend: {}, api: "shop/current", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, staff: { dataSend: { txt_staff_id: 0 }, api: "staff/id", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, product: { dataSend: { txt_product_id: 0 }, api: "product/id", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, relation: { dataSend: { txt_referral_id: 0 }, api: "referral/relation", ok: false, dataArray: [], dataArrayState: { load: false, done: false } } }; $scope.data = { attribute: { state: false, productId: "", dataArray: [] }, attribute_custom: { state: false, dataArray: [] }, reward: { quantity_name: 'reward', type_id: "0", reward_amount: 0, reward_percent: 0, reward_every_price: 0, point_reward: 0 }, quantity: { quantity_name: 'quantity', quantity_min: 1, quantity_max: 1, quantity_input: 1, quantity_select: [] }, product_price: { price_name: 'product_price', price: 0, price_ecimals: 0, total_stock: 0 }, product_compare_price: { price_name: 'product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_price: { price_name: 'sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_price: { price_name: 'sum_product_compare_price', price: 0, price_ecimals: 0, total_stock: 0 }, sum_product_compare_minus_sum_product_price: { price_name: 'sum_product_compare_minus_sum_product_price', price: 0, price_ecimals: 0, total_stock: 0 }, detail: { active: '0', dataArray: [{ index: '0', state: true, en: ($scope.description != undefined && $scope.description != "") ? $scope.description : 'Description', th: '', data: '', dataArray: [] }, { index: '1', state: true, en: ($scope.info != undefined && $scope.info != "") ? $scope.info : 'Info', th: '', data: '', dataArray: [] }, { index: '2', state: true, en: ($scope.specification != undefined && $scope.specification != "") ? $scope.specification : 'Specification', th: '', data: '', dataArray: [] }] }, promotion : { promotion_id : '0' } }; $scope.setBuy = { state_active: false, state_process: false, state_step: 0, state_data_font_color: "", state_data_background_color: "", stepArray: [{ step: 0, name: "unset", icon: $scope._icebuyicon, state: $scope._buytext, data_font_color: "", data_background_color: "" }, { step: 1, name: "load", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 2, name: "pass", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 3, name: "error", icon: "", state: "", data_font_color: "", data_background_color: "" }, { step: 4, name: "cart", icon: "", state: $scope._viewcarttext, data_font_color: "", data_background_color: "primary_darkest" }] }; /* - get api product/id start - */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.product.dataArrayState = res_state; $scope.getData().getProductId(res_params, function(res_product_id) { $scope.dataApi.product.dataSend.txt_product_id = (res_product_id != false) ? res_product_id : 0; $scope.getData().dataSend($scope.dataApi.product.api, $scope.dataApi.product.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_product, res_state) { $scope.dataApi.product.ok = res_ok; if ($scope._imageappcoverchecked) { var images = []; angular.forEach(get_res_api_product.data.product_image,function(image,index_image){ if (!image.image_app_cover_checked) { images.push(image) } }); get_res_api_product.data.product_image = images; } angular.element('.load-effect').removeClass('is-active'); $scope.dataApi.product.dataArray = get_res_api_product.data; $scope.getData().consoleLog("get_res_api_product", get_res_api_product); $scope.dataApi.product.dataArrayState = res_state; /* -- get api shop/current to reward -- */ if (res_ok) { $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.reward.dataArrayState = res_state; $scope.getData().dataSend($scope.dataApi.reward.api, $scope.dataApi.reward.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_shop, res_state) { $scope.dataApi.reward.ok = res_ok; $scope.dataApi.reward.dataArray = get_res_api_shop.data; $scope.dataApi.reward.dataArrayState = res_state; $scope.getReward().createReward($scope.dataApi.product.dataArray.product_reward, get_res_api_shop.data.shop_point_config, function(res_reward) { $scope.data.reward.type_id = res_reward.type_id; $scope.data.reward.reward_amount = res_reward.amount; $scope.data.reward.reward_percent = res_reward.percent; $scope.data.reward.reward_every_price = res_reward.every_price; /* --- Wait product/id ,shop/current --- */ /* ---- get attribute ---- */ $scope.getAttribute().productAttribute(get_res_api_product.data.product_attribute, function(res_attribute) { $scope.data.attribute.dataArray = res_attribute; $scope.getAttribute().checkMinPrices(get_res_api_product, res_attribute, function(res_data_price, res_state) { $scope.data.attribute.state = res_state; $scope.data.product_price = res_data_price.product_price; $scope.data.product_compare_price = res_data_price.product_compare_price; $scope.data.sum_product_price = res_data_price.sum_product_price; $scope.data.sum_product_compare_price = res_data_price.sum_product_compare_price; $scope.data.sum_product_compare_minus_sum_product_price = res_data_price.sum_product_compare_minus_sum_product_price; $scope.getReward().getCalculator($scope.data.sum_product_price, $scope.data.reward, function(res_point_reward) { $scope.data.reward.point_reward = res_point_reward; }); /* ----- stock ----- */ $scope.data.quantity.quantity_max = res_data_price.product_price.total_stock; $scope.data.quantity.quantity_select = []; for (var i = 0; i < res_data_price.product_price.total_stock; i++) { $scope.data.quantity.quantity_select.push(i + 1); } /* ----- stock ----- */ }); }); /* ---- get attribute ---- */ /* ---- get attribute custom ---- */ $scope.getAttributeCustom().createArray(get_res_api_product.data.product_custom_templates, function(res_custom_attribute, res_state) { $scope.data.attribute_custom.state = res_state; $scope.data.attribute_custom.dataArray = res_custom_attribute; }); /* ---- get attribute custom ---- */ /* ---- get detail ---- */ $scope.getDetail().getDetail(get_res_api_product.data, function(res_description, res_info, res_state_info, res_specificatio, res_state_specificatio) { $scope.data.detail.dataArray[0].data = res_description; $scope.data.detail.dataArray[1].data = res_info; $scope.data.detail.dataArray[1].state = res_state_info; $scope.data.detail.dataArray[2].dataArray = res_specificatio; $scope.data.detail.dataArray[2].state = res_state_specificatio; }); /* ---- get detail ---- */ /* ---- update state ---- */ $scope.getBuy().updateState($scope.dataApi.product.dataArray.product_id); /* ---- update state ---- */ /* --- Wait product/id ,shop/current --- */ }); }); }); }); /* -- get api shop/current to reward -- */ /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.relation.dataArrayState = res_state; $scope.getData().getReferralId(get_res_api_product.data.product_referral_display, function(res_referral_id) { $scope.dataApi.relation.dataSend.txt_referral_id = res_referral_id; $scope.getData().dataSend($scope.dataApi.relation.api, $scope.dataApi.relation.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_referral, res_state) { $scope.dataApi.relation.ok = res_ok; $scope.dataApi.relation.dataArray = (res_referral_id != 0) ? get_res_api_referral.data : []; $scope.dataApi.relation.dataArrayState = res_state; }); }); }); }); /* -- res_referral_id from product/id to txt_referral_id get api referral/relation -- */ /* -- product_staff_id from product/id to txt_staff_id get api staff/id -- */ $scope.getData().getRouteParams(function(res_params, res_state) { $scope.getData().getStaffId(get_res_api_product.data.product_staff_id, function(res_staff) { if (res_staff.status) { $scope.dataApi.staff.dataArrayState = res_state; $scope.dataApi.staff.dataSend.txt_staff_id = res_staff.staff_id; $scope.getData().dataSend($scope.dataApi.staff.api, $scope.dataApi.staff.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, res, res_state) { $scope.dataApi.staff.ok = res_ok; $scope.dataApi.staff.dataArray = res.data; $scope.getData().getNameUrl(res.data.staff_first_name, function(res_staff_first_name_url) { $scope.dataApi.staff.dataArray.staff_first_name_url = res_staff_first_name_url; $scope.dataApi.staff.dataArrayState = res_state; }); }); }); } }); }); /* -- product_staff_id from product/id to txt_staff_id get api staff/id -- */ } else { /* ok = false */ if ($scope.dataApi.product.dataArray.length != 0) { /* product deal to product original */ if ($scope.dataApi.product.dataArray.product_set_array.length != 0) { $scope.countDown().getNameUrl($scope.dataApi.product.dataArray.product_set_array[0].product_title, function(res_name) { $scope.pages().pageUrl("product-detail", $scope.dataApi.product.dataArray.product_set_array[0].product_id, res_name); }); } else { $scope.pages().pageName("home"); } } else { /* product null */ $scope.pages().pageName("home"); } } }); }); }); }); /* - get api product/id end - */ /* get product api */ }; return promise; });_ui_share_app.directive('componentProductDiscount', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductDiscount'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'feature':'@feature', 'badgeid':'@badgeid', 'badgetext':'@badgetext', 'imgpath':'@imgpath', 'margin':'@margin', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval) { $scope.use_feature = (typeof $scope.feature !== 'undefined' && $scope.feature == 'true') ? true : false; /** * Check if object array available for "website application" or "Mobile application" or "Featured" * @params object array * return true | false (default) */ $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope._showFeature = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 16) { r = true; break; } } return r; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* Dummy */ $scope.getDummyArray = function(){ var r = []; var max = 6; for(var i = 0; i < max; i++){ r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}], product_badge:[{badge_id:18}], callback_array:true }); } return r; }; $scope.data = []; $scope.data_discount = []; $scope.data_done = false; /* Get referral data (all) * @params none * @return array */ $scope.getData = function(badgeId){ $scope.data = []; $scope.data_discount = []; $scope.data_discount.discount_price = 0; $scope.data_done = false; var filterJson = {'badge_id_array':[18]}; if($scope.use_feature){ filterJson.badge_id_array.push(16); } var d = { 'cur_page':1, 'per_page':8, 'txt_filter_json':JSON.stringify(filterJson), }; GAEAPI.get('product/lists',d,$scope).then(function(e){ if(e.ok == 1){ if(e.data.dataList.length > 0){ $scope.data = e.data.dataList; for (var i = 0; i < e.data.dataList.length; i++) { console.log("test_discount : ",i,e.data.dataList[i].product_discount.length , e.data.dataList[i].product_discount); if(e.data.dataList[i].product_discount.length == undefined && e.data.dataList[i].product_discount){ console.log("test_discount",e.data.dataList[i].product_discount); $scope.data_discount.push(e.data.dataList[i]); if(e.data.dataList[i].product_discount.discount_price != 0){ $scope.data_discount[i].discount_price = (e.data.dataList[i].product_price-e.data.dataList[i].product_discount.discount_price); }else if(e.data.dataList[i].product_discount.discount_price == 0 && e.data.dataList[i].product_discount.discount_percent != 0){ $scope.data_discount[i].discount_price = (e.data.dataList[i].product_price-((e.data.dataList[i].product_price*e.data.dataList[i].product_discount.discount_percent)/100)); } console.log("test_discount_price",$scope.data_discount[i].discount_price); } } } else { var dummy = $scope.getDummyArray(); $scope.data = dummy; } $scope.buildImageSlider($scope.data); $scope.data_done = true; } }); }; /* Get referral data (by referral_id) * @params id = referral_id * @return array */ $scope.getDataReferral = function(id){ $scope.data = []; $scope.data_done = false; var d = { 'txt_referral_id':id }; GAEAPI.get('referral/id_map',d,$scope).then(function(e){ if(e.ok == 1){ $scope.data[0] = e.data; $scope.data_done = true; $scope.buildImageSlider($scope.data); } }); }; /* * params listener * @params newValue * @params oldValue * @return function */ $scope.$watch('badgeid', function (newValue, oldValue) { if (!newValue){ return; } $scope.getData(newValue); }); /* * check if image array exist or build dummy image array * @params arrayObject = object array * @return array */ $scope.buildImageSlider = function(){ var imageArray = function(){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_1.jpg'}, /*{'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/gallery_2.jpg'},*/ ]; }; var imageBannerArray = function(){ return [ {'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_1.jpg'}, /*{'image_url':'extensions/themes/gae_myhappyphone301/staticfiles/images/default/banner_cat_2.jpg'},*/ ]; }; angular.forEach($scope.data, function(item,key){ if(typeof item.product_image == 'undefined'){ item.product_image = []; } /*if(typeof item.referral_image_banner == 'undefined'){ item.referral_image_banner = []; }*/ if(!item.product_image.length){ item.product_image = imageArray(); } /*item.referral_image_banner = imageBannerArray();*/ }); }; /* Make Carousel */ $scope._makeProductToCarousel = function (keyCustom) { var elementName = '[data-id="' + keyCustom + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, "", keyCustom); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(){ return "-" + (($('.row.slick-slider[data-id="'+$scope._uniqueKey+'"]').height() / 2) + 34) + "px"; }; /* Carousel Arrow Click */ $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; /* Carousel Arrow Click */ $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { if($('[data-id*="gallery-"]').length){ $('[data-id*="gallery-"]').not('.slick-initialized').each(function(Key,Object){ if($(this).find('.imageItem').length > 0){ $scope._makeProductToCarousel($(this).attr('data-id')); } }); } }); /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); if (typeof $productTimingRequest == 'undefined') { var $productTimingRequest = { request: 0, data: 0, timeMemory: null, checkAllDone: function() { console.log("checkAllDone", this.data, this.request); if (this.data > 0 && this.data >= this.request) { $('.all-load').addClass('active'); $('.all-content').addClass('active'); this.timeMemory = setTimeout(function() { $('.all-content').addClass('shown'); window.clearTimeout(this.timeMemory); }, 650); } }, instantDisplay: function() { console.log("checkAllDone: not match => display"); $('.all-load').addClass('active'); $('.all-content').addClass('active'); $('.all-content').addClass('shown'); this.timeMemory = null; } }; } var _countHide = 0; _ui_share_app.directive('componentProductLayout', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductLayout'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', request: '@type', carousel: '@carousel', referral: '@referral', imgcart: '@imgcart', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_second': '?textSecond', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.forbidden = false; $scope._config = []; $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.use_carousel = (typeof $scope.carousel !== 'undefined' && $scope.carousel == 'true') ? true : false; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.productData = []; $scope.productDataload = false; $scope.type = $scope.request; $scope.done = false; /* GET product list in category (feature *any) */ $scope._get_category_feature = function() { $scope.productData = []; var dataSendCat = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify([{ 'badge_id_array': [16] }]) }; /* badge_sort_index_asc*/ GAEAPI.get('referral/lists', dataSendCat, $scope).then(function(resultCategory) { var ref = []; for (var i = 0; i < resultCategory.data.dataList.length; i++) { for (var ii = 0; ii < resultCategory.data.dataList[i].referral_badge.length; ii++) { if (resultCategory.data.dataList[i].referral_badge[ii].badge_id == 16) { ref.push(parseInt(resultCategory.data.dataList[i].referral_id)); break; } } } $scope.productDataload = false; var jsonFilter = { 'referral_id_array_or': ref, 'badge_id_array': [18] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.productData = e.data.dataList; $scope.productDataload = true; } }); }); }; /* GET product list by badge id (reccommend,new arriaval, best seller, feature) */ $scope._get_product_by_badge = function(badgeId) { $scope.productData = []; $scope.productDataload = false; var jsonFilter = { 'badge_id_array': [18, badgeId] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; /*product_lastest_create */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.productData = e.data.dataList; $scope.productDataload = true; } }); }; /* GET product list by each category (1st level) */ $scope._get_product_list_by_category = function(referral_id) { $scope.productDataload = false; $productTimingRequest.request = $productTimingRequest.request + 1; var j = { 'badge_id_array': [18], 'referral_id_array': [referral_id] }; var d = { 'cur_page': 1, 'per_page': 30, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(j) }; /* root_category_index_asc */ console.log("Fetching 1", $scope.referral); GAEAPI.get('product/lists', d, $scope).then(function(e) { $scope.productDataload = true; $scope.productData = e.data.dataList; $productTimingRequest.data = $productTimingRequest.data + 1; $productTimingRequest.checkAllDone(); if (e.data.dataList.length <= 0 && $routeParams.referral_id == referral_id) { /* window.location.href="home";*/ } else if (e.data.dataList.length <= 0) { $('div[data-id="' + $scope.referral + '"]').hide(); } if (typeof $routeParams.section !== 'undefined') { // alert($routeParams.section); $timeout(function() { $('html, body').animate({ scrollTop: $("div[id='" + $routeParams.section + "']").offset().top - 250 }, 200); }, 200); } console.log("Fetching 2", $scope.referral, " : result :", $scope.productData); }); }; $scope.$watch('type', function(newValue, oldValue) { if (!newValue) { return; } if (newValue == 'category_feature') { /* Featured Product */ /*return $scope._get_category_feature();*/ return $scope._get_product_by_badge(16); } if (newValue == 'product_newarrival' || newValue == 'new_arrival') { /* New Arrival */ return $scope._get_product_by_badge(72); } if (newValue == 'product_bestseller' || newValue == 'best_seller') { /* New Arrival */ return $scope._get_product_by_badge(75); } if (newValue == 'product_feature' || newValue == 'product_recommend') { /* Recommend */ return $scope._get_product_by_badge(74); } if (newValue == 'product_list_by_category') { return $scope._get_product_list_by_category($scope.referral); } }); $scope.shopid = ''; $scope.getShopid = function() { $scope.shopid = CUR_THEME.shop_id(); }; $scope.getShopid(); $scope.initSlider = function() { var elementName = '.row-product[data-id="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, centerMode: true, centerPadding: '0px', slidesToShow: 3, slidesToScroll: 1, dots: false, arrows: false, infinite: true, responsive: [{ breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 2 } }] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(v) { return "-" + ($('.row-product[data-id="' + $scope._uniqueKey + '"]').height() / 2) + v + "px"; }; /* Calculate Product mobile for Arrows */ $scope.calculateProductBlockMobile = function(v) { return $('.row-product[data-id="' + $scope._uniqueKey + '"]').height() / 2; }; $rootScope.$on('repeatend', function() { if ($scope.use_carousel) { var t = $interval(function() { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function() { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); } }); $scope.checkHideCondition = function(referral_id) { return true; if ($location.path() != '/' && $location.path() !== '/home') { if (typeof $routeParams.root_id !== 'undefined' && $routeParams.root_id > 0 && $routeParams.root_id != referral_id) { return false; /* hide */ } return true; } return true; }; }; return promise; }); var _countHide = 0; _ui_share_app.directive('componentProductLayoutA', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductLayoutA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', request: '@type', carousel: '@carousel', referral: '@referral', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first':'?textFirst', 'text_second':'?textSecond', }; promise.link = function (scope, element, attr) {}; promise.controller = function ($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.use_carousel = (typeof $scope.carousel !== 'undefined' && $scope.carousel == 'true') ? true : false; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.productData = []; $scope.type = $scope.request; /* GET product list in category (feature *any) */ $scope._get_category_feature = function(){ $scope.productData = []; var dataSendCat = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify([{'badge_id_array': [16]}]) }; /* badge_sort_index_asc*/ GAEAPI.get('referral/lists', dataSendCat).then(function(resultCategory){ var ref = []; for(var i = 0; i < resultCategory.data.dataList.length; i++){ for(var ii = 0; ii < resultCategory.data.dataList[i].referral_badge.length; ii++){ if(resultCategory.data.dataList[i].referral_badge[ii].badge_id == 16){ ref.push(parseInt(resultCategory.data.dataList[i].referral_id)); break; } } } var jsonFilter = { 'referral_id_array_or': ref, 'badge_id_array': [18] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'product_title_a-z', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend).then(function(e){ if(e.ok == 1){ $scope.productData = e.data.dataList; } }); }); }; /* GET product list by badge id (reccommend,new arriaval, best seller, feature) */ $scope._get_product_by_badge = function(badgeId){ $scope.productData = []; var jsonFilter = { 'badge_id_array': [18,badgeId] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'badge_sort_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; /*product_lastest_create */ GAEAPI.get('product/lists', dataSend).then(function(e){ if(e.ok == 1){ $scope.productData = e.data.dataList; } }); }; /* GET product list by each category (1st level) */ $scope._get_product_list_by_category = function(referral_id){ var j = { 'badge_id_array': [18], 'referral_id_array': [referral_id] }; var d = { 'cur_page': 1, 'per_page': 30, 'txt_sortby':'root_category_index_0-9', 'txt_filter_json': JSON.stringify(j) }; /* root_category_index_asc */ console.log("Fetching ", $scope.referral); if(CUR_THEME.shop_id() == 500){ $scope.text_first = 'testtt'; $http.get('https://missmonribs.getappeasy.com/store/api/v1/product/lists',{params:d}).then(function(res){ var e = res.data; $scope.productData = e.data.dataList; console.log("Fetching ", $scope.referral, " : result :", $scope.productData); if($scope.productData.length <= 0 && $routeParams.referral_id == referral_id){ return $location.path("/home"); } }); } else { GAEAPI.get('product/lists',d).then(function(e){ $scope.productData = e.data.dataList; console.log("Fetching ", $scope.referral, " : result :", e); }); } }; $scope.$watch('type', function(newValue,oldValue){ if(!newValue){ return; } if(newValue == 'category_feature'){ /* Featured Product */ /*return $scope._get_category_feature();*/ return $scope._get_product_by_badge(16); } if(newValue == 'product_newarrival' || newValue == 'new_arrival') { /* New Arrival */ return $scope._get_product_by_badge(72); } if(newValue == 'product_feature' || newValue == 'product_recommend') { /* Recommend */ return $scope._get_product_by_badge(74); } if(newValue == 'product_list_by_category'){ return $scope._get_product_list_by_category($scope.referral); } }); $scope._makeProductToCarousel = function () { var elementName = '[data-id="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 4, slidesToScroll: 4, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, responsive: [ { breakpoint: 769, settings: { slidesToShow: 3, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false } } ] }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(v){ return "-" + ($('[data-id="'+$scope._uniqueKey+'"]').height() / 2) + "."+ v + "px"; }; /* Calculate Product mobile for Arrows */ $scope.calculateProductBlockMobile = function(v){ return $('[data-id="'+$scope._uniqueKey+'"]').height() / 2; }; $rootScope.$on('repeatend', function() { if($('[data-id="'+$scope._uniqueKey+'"]').not('.slick-initialized') && $scope.use_carousel){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); $scope.checkHideCondition = function(referral_id){ return true; if($location.path() != '/' && $location.path() !== '/home'){ if(typeof $routeParams.root_id !== 'undefined' && $routeParams.root_id > 0 && $routeParams.root_id != referral_id){ return false; /* hide */ } return true; } return true; }; }; return promise; }); var _countHide = 0; _ui_share_app.directive('componentProductLayoutB', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductLayoutB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', request: '@type', carousel: '@carousel', referral: '@referral', lesspad: '@lesspad', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first':'?textFirst', 'text_second':'?textSecond', }; promise.link = function (scope, element, attr) {}; promise.controller = function ($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.use_carousel = (typeof $scope.carousel !== 'undefined' && $scope.carousel == 'true') ? true : false; $scope.use_lesspad = (typeof $scope.lesspad !== 'undefined' && $scope.lesspad == 'true') ? true : false; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.productData = []; $scope.type = $scope.request; /* GET product list in category (feature *any) */ $scope._get_category_feature = function(){ $scope.productData = []; var dataSendCat = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify([{'badge_id_array': [16]}]) }; /* badge_sort_index_asc*/ GAEAPI.get('referral/lists', dataSendCat).then(function(resultCategory){ var ref = []; for(var i = 0; i < resultCategory.data.dataList.length; i++){ for(var ii = 0; ii < resultCategory.data.dataList[i].referral_badge.length; ii++){ if(resultCategory.data.dataList[i].referral_badge[ii].badge_id == 16){ ref.push(parseInt(resultCategory.data.dataList[i].referral_id)); break; } } } var jsonFilter = { 'referral_id_array_or': ref, 'badge_id_array': [18] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'product_title_a-z', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend).then(function(e){ if(e.ok == 1){ $scope.productData = e.data.dataList; console.log("tiuuiy111",$scope.productData); } }); }); }; /* GET product list by badge id (reccommend,new arriaval, best seller, feature) */ $scope._get_product_by_badge = function(badgeId){ $scope.productData = []; var jsonFilter = { 'badge_id_array': [18,badgeId] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'badge_sort_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; /*product_lastest_create */ GAEAPI.get('product/lists', dataSend).then(function(e){ if(e.ok == 1){ $scope.productData = e.data.dataList; console.log("tiuuiy222",$scope.productData); } }); }; /* GET product list by each category (1st level) */ $scope._get_product_list_by_category = function(referral_id){ var j = { 'badge_id_array': [18], 'referral_id_array': [referral_id] }; var d = { 'cur_page': 1, 'per_page': 30, 'txt_sortby':'root_category_index_0-9', 'txt_filter_json': JSON.stringify(j) }; /* root_category_index_asc */ console.log("Fetching ", $scope.referral); if(CUR_THEME.shop_id() == 500){ $scope.text_first = 'testtt'; $http.get('https://missmonribs.getappeasy.com/store/api/v1/product/lists',{params:d}).then(function(res){ var e = res.data; $scope.productData = e.data.dataList; console.log("Fetching ", $scope.referral, " : result :", $scope.productData); if($scope.productData.length <= 0 && $routeParams.referral_id == referral_id){ return $location.path("/home"); } }); } else { GAEAPI.get('product/lists',d).then(function(e){ $scope.productData = e.data.dataList; console.log("Fetching ", $scope.referral, " : result :", e); console.log("tiuuiy333",$scope.productData); }); } }; $scope.$watch('type', function(newValue,oldValue){ if(!newValue){ return; } if(newValue == 'category_feature'){ /* Featured Product */ /*return $scope._get_category_feature();*/ return $scope._get_product_by_badge(16); } if(newValue == 'product_newarrival' || newValue == 'new_arrival') { /* New Arrival */ return $scope._get_product_by_badge(72); } if(newValue == 'product_feature' || newValue == 'product_recommend') { /* Recommend */ return $scope._get_product_by_badge(74); } if(newValue == 'product_list_by_category'){ return $scope._get_product_list_by_category($scope.referral); } }); $scope._makeProductToCarousel = function () { var elementName = '[data-id="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 3, slidesToScroll: 3, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, responsive: [ { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false } } ] }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(v){ return "-" + ($('[data-id="'+$scope._uniqueKey+'"]').height() / 2) + v + "px"; }; /* Calculate Product mobile for Arrows */ $scope.calculateProductBlockMobile = function(v){ return $('[data-id="'+$scope._uniqueKey+'"]').height() / 2; }; $rootScope.$on('repeatend', function() { if($('[data-id="'+$scope._uniqueKey+'"]').not('.slick-initialized') && $scope.use_carousel){ $timeout(function(){ $scope._makeProductToCarousel(); }, 500); } }); $scope.checkHideCondition = function(referral_id){ return true; if($location.path() != '/' && $location.path() !== '/home'){ if(typeof $routeParams.root_id !== 'undefined' && $routeParams.root_id > 0 && $routeParams.root_id != referral_id){ return false; /* hide */ } return true; } return true; }; }; return promise; }); var _countHide = 0; _ui_share_app.directive('componentProductLayoutC', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductLayoutC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', request: '@type', carousel: '@carousel', referral: '@referral', imgcart: '@imgcart', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_second': '?textSecond', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.forbidden = false; $scope._config = []; $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.use_carousel = (typeof $scope.carousel !== 'undefined' && $scope.carousel == 'true') ? true : false; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.productData = []; $scope.productDataload = false; $scope.type = $scope.request; $scope.done = false; /* GET product list in category (feature *any) */ $scope._get_category_feature = function() { $scope.productData = []; var dataSendCat = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify([{ 'badge_id_array': [16] }]) }; /* badge_sort_index_asc*/ GAEAPI.get('referral/lists', dataSendCat, $scope).then(function(resultCategory) { var ref = []; for (var i = 0; i < resultCategory.data.dataList.length; i++) { for (var ii = 0; ii < resultCategory.data.dataList[i].referral_badge.length; ii++) { if (resultCategory.data.dataList[i].referral_badge[ii].badge_id == 16) { ref.push(parseInt(resultCategory.data.dataList[i].referral_id)); break; } } } $scope.productDataload = false; var jsonFilter = { 'referral_id_array_or': ref, 'badge_id_array': [18] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.productData = e.data.dataList; $scope.productDataload = true; } }); }); }; /* GET product list by badge id (reccommend,new arriaval, best seller, feature) */ $scope._get_product_by_badge = function(badgeId) { $scope.productData = []; $scope.productDataload = false; var jsonFilter = { 'badge_id_array': [18, badgeId] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; /*product_lastest_create */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.productData = e.data.dataList; $scope.productDataload = true; } }); }; /* GET product list by each category (1st level) */ $scope._get_product_list_by_category = function(referral_id) { // $scope.productData = []; $scope.productDataload = false; $productTimingRequest.request = $productTimingRequest.request + 1; var f_first = { 'txt_referral_id': referral_id } GAEAPI.get('referral/id_map', f_first, $scope).then(function(e) { if (e.ok == 1) { if(e.data.referral_sub_array.length > 0){ $scope.productDataload = true; $scope.productData = e.data.referral_sub_array; console.log("pop kai sod test 1 :",$scope.productData); $scope.havsub = true; }else{ var j = { 'badge_id_array': [18], 'referral_id_array': [referral_id] }; var d = { 'cur_page': 1, 'per_page': 30, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(j) }; $scope.havsub = false; console.log("Fetching 1", $scope.referral); GAEAPI.get('product/lists', d, $scope).then(function(e) { $scope.productDataload = true; $scope.productData = e.data.dataList; console.log("pop kai sod test 2 :",$scope.productData); $productTimingRequest.data = $productTimingRequest.data + 1; $productTimingRequest.checkAllDone(); if (e.data.dataList.length <= 0 && $routeParams.referral_id == referral_id) { /* window.location.href="home";*/ } else if (e.data.dataList.length <= 0) { $('div[data-id="' + $scope.referral + '"]').hide(); } if (typeof $routeParams.section !== 'undefined') { // alert($routeParams.section); $timeout(function() { $('html, body').animate({ scrollTop: $("div[id='" + $routeParams.section + "']").offset().top - 250 }, 200); }, 200); } console.log("Fetching 2", $scope.referral, " : result :", $scope.productData); }); } } }); /* root_category_index_asc */ }; $scope.$watch('type', function(newValue, oldValue) { if (!newValue) { return; } if (newValue == 'category_feature') { /* Featured Product */ /*return $scope._get_category_feature();*/ return $scope._get_product_by_badge(16); } if (newValue == 'product_newarrival' || newValue == 'new_arrival') { /* New Arrival */ return $scope._get_product_by_badge(72); } if (newValue == 'product_bestseller' || newValue == 'best_seller') { /* New Arrival */ return $scope._get_product_by_badge(75); } if (newValue == 'product_feature' || newValue == 'product_recommend') { /* Recommend */ return $scope._get_product_by_badge(74); } if (newValue == 'product_list_by_category') { // $scope.havsub = false; return $scope._get_product_list_by_category($scope.referral); } }); $scope.shopid = ''; $scope.getShopid = function() { $scope.shopid = CUR_THEME.shop_id(); }; $scope.getShopid(); $scope.initSlider = function() { var elementName = '.row-product[data-id="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, centerMode: true, centerPadding: '0px', slidesToShow: 3, slidesToScroll: 1, dots: false, arrows: false, infinite: true, responsive: [{ breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 2 } }] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(v) { return "-" + ($('.row-product[data-id="' + $scope._uniqueKey + '"]').height() / 2) + v + "px"; }; /* Calculate Product mobile for Arrows */ $scope.calculateProductBlockMobile = function(v) { return $('.row-product[data-id="' + $scope._uniqueKey + '"]').height() / 2; }; $rootScope.$on('repeatend', function() { if ($scope.use_carousel) { var t = $interval(function() { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function() { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); } }); $scope.checkHideCondition = function(referral_id) { return true; if ($location.path() != '/' && $location.path() !== '/home') { if (typeof $routeParams.root_id !== 'undefined' && $routeParams.root_id > 0 && $routeParams.root_id != referral_id) { return false; /* hide */ } return true; } return true; }; }; return promise; });_ui_share_app.factory('$componentProductLayoutMain', function componentProductLayoutMain($routeParams, $timeout) { return });_ui_share_app.directive('componentProductLayoutMainA', function($rootScope, $routeParams) { var templateName = 'componentProductLayoutMainA'; var componentMain = 'componentProductLayoutMain'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', request: '@type', carousel: '@carousel', referral: '@referral', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_second': '?textSecond', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.forbidden = false; $scope._config = []; $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.use_carousel = (typeof $scope.carousel !== 'undefined' && $scope.carousel == 'true') ? true : false; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._viewRouteParams = function () { return $routeParams || false; }; $scope.productData = []; $scope.productDataload = false; $scope.type = $scope.request; /* GET product list in category (feature *any) */ $scope._get_category_feature = function() { $scope.productData = []; var dataSendCat = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify([{ 'badge_id_array': [16] }]) }; /* badge_sort_index_asc*/ GAEAPI.get('referral/lists', dataSendCat, $scope).then(function(resultCategory) { var ref = []; for (var i = 0; i < resultCategory.data.dataList.length; i++) { for (var ii = 0; ii < resultCategory.data.dataList[i].referral_badge.length; ii++) { if (resultCategory.data.dataList[i].referral_badge[ii].badge_id == 16) { ref.push(parseInt(resultCategory.data.dataList[i].referral_id)); break; } } } $scope.productDataload = false; var jsonFilter = { 'referral_id_array_or': ref, 'badge_id_array': [18] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'product_title_a-z', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.productData = e.data.dataList; $scope.productDataload = true; } }); }); }; $scope.categoryData = []; $scope._getCategory = function(badgeId) { var dataSend = { 'txt_referral_type_id': 11 }; GAEAPI.get('referral/map', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.categoryData = e.data; } }); }; $scope._getCategory(); /* GET product list by badge id (reccommend,new arriaval, best seller, feature) */ $scope._get_product_by_badge = function(badgeId) { $scope.productData = []; $scope.productDataload = false; var jsonFilter = { 'badge_id_array': [18, badgeId] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'badge_sort_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; /*product_lastest_create */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.productData = e.data.dataList; $scope.productDataload = true; } }); }; /* GET product list by each category (1st level) */ $scope._get_product_list_by_category = function(referral_id) { $scope.productDataload = false; $productTimingRequest.request = $productTimingRequest.request + 1; var j = { 'badge_id_array': [18], 'referral_id_array': [referral_id] }; var d = { 'cur_page': 1, 'per_page': 30, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(j) }; /* root_category_index_asc */ console.log("Fetching 1", $scope.referral); GAEAPI.get('product/lists', d, $scope).then(function(e) { $scope.productDataload = true; $scope.productData = e.data.dataList; $productTimingRequest.data = $productTimingRequest.data + 1; $productTimingRequest.checkAllDone(); if (e.data.dataList.length <= 0 && $routeParams.referral_id == referral_id) { /* window.location.href="home";*/ } else if (e.data.dataList.length <= 0) { $('div[data-id="' + $scope.referral + '"]').hide(); } console.log("Fetching 2", $scope.referral, " : result :", $scope.productData); }); }; $scope.$watch('type', function(newValue, oldValue) { if (!newValue) { return; } if (newValue == 'category_feature') { /* Featured Product */ /*return $scope._get_category_feature();*/ return $scope._get_product_by_badge(16); } if (newValue == 'product_newarrival' || newValue == 'new_arrival') { /* New Arrival */ return $scope._get_product_by_badge(72); } if (newValue == 'product_feature' || newValue == 'product_recommend') { /* Recommend */ return $scope._get_product_by_badge(74); } if (newValue == 'product_list_by_category') { return $scope._get_product_list_by_category($scope.referral); } }); $scope._makeProductToCarousel = function() { var elementName = '[data-id="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 3, slidesToScroll: 3, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, responsive: [{ breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false } }] }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(v) { return "-" + ($('.row-product[data-id="' + $scope._uniqueKey + '"]').height() / 2) + v + "px"; }; /* Calculate Product mobile for Arrows */ $scope.calculateProductBlockMobile = function(v) { return $('.row-product[data-id="' + $scope._uniqueKey + '"]').height() / 2; }; $rootScope.$on('repeatend', function() { if ($('[data-id="' + $scope._uniqueKey + '"]').not('.slick-initialized') && $scope.use_carousel) { $timeout(function() { $scope._makeProductToCarousel(); }, 500); } }); $scope.arrayDataDOno = function(id, indata) { var dataSend = 0; for (var i = 0; i < indata.length; i++) { if (indata[i].product_referral_display.category[0].referral_parent_id == id) { dataSend++; } } return dataSend; }; $scope.arrayDataDTwo = function(id, indata) { var dataSend = 0; for (var i = 0; i < indata.length; i++) { if (indata[i].product_referral_display.category[0].referral_id == id) { dataSend++; } } return dataSend; }; $scope.checkHideCondition = function(referral_id) { return true; if ($location.path() != '/' && $location.path() !== '/home') { if (typeof $routeParams.root_id !== 'undefined' && $routeParams.root_id > 0 && $routeParams.root_id != referral_id) { return false; /* hide */ } return true; } return true; }; }; return promise; }); _ui_share_app.directive('componentProductLayoutZ', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductLayoutZ'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', request: '@type', carousel: '@carousel', referral: '@referral', imgcart: '@imgcart', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_second': '?textSecond', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.forbidden = false; $scope._config = []; $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.use_carousel = (typeof $scope.carousel !== 'undefined' && $scope.carousel == 'true') ? true : false; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.productData = []; $scope.productDataload = false; $scope.type = $scope.referral; $scope.done = false; /* GET product list in category (feature *any) */ $scope._get_category_feature = function() { $scope.productData = []; var dataSendCat = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify([{ 'badge_id_array': [16] }]) }; /* badge_sort_index_asc*/ GAEAPI.get('referral/lists', dataSendCat, $scope).then(function(resultCategory) { var ref = []; for (var i = 0; i < resultCategory.data.dataList.length; i++) { for (var ii = 0; ii < resultCategory.data.dataList[i].referral_badge.length; ii++) { if (resultCategory.data.dataList[i].referral_badge[ii].badge_id == 16) { ref.push(parseInt(resultCategory.data.dataList[i].referral_id)); break; } } } $scope.productDataload = false; var jsonFilter = { 'referral_id_array_or': ref, 'badge_id_array': [18] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.productData = e.data.dataList; $scope.productDataload = true; } }); }); }; /* GET product list by badge id (reccommend,new arriaval, best seller, feature) */ $scope._get_product_by_badge = function(badgeId) { $scope.productData = []; $scope.productDataload = false; var jsonFilter = { 'badge_id_array': [18, badgeId] }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; /*product_lastest_create */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.productData = e.data.dataList; $scope.productDataload = true; } }); }; /* GET product list by each category (1st level) */ $scope._get_product_list_by_category = function(referral_id) { $scope.productDataload = false; $productTimingRequest.request = $productTimingRequest.request + 1; var j = { 'badge_id_array': [18], 'referral_id_array': [referral_id] }; var d = { 'cur_page': 1, 'per_page': 30, 'txt_sortby': 'root_category_index_asc', 'txt_filter_json': JSON.stringify(j) }; /* root_category_index_asc */ console.log("Fetching 1", $scope.referral); GAEAPI.get('product/lists', d, $scope).then(function(e) { $scope.productDataload = true; $scope.productData = e.data.dataList; $productTimingRequest.data = $productTimingRequest.data + 1; $productTimingRequest.checkAllDone(); if (e.data.dataList.length <= 0 && $routeParams.referral_id == referral_id) { /* window.location.href="home";*/ } else if (e.data.dataList.length <= 0) { $('div[data-id="' + $scope.referral + '"]').hide(); } if (typeof $routeParams.section !== 'undefined') { // alert($routeParams.section); $timeout(function() { $('html, body').animate({ scrollTop: $("div[id='" + $routeParams.section + "']").offset().top - 250 }, 200); }, 200); } console.log("Fetching 2", $scope.referral, " : result :", $scope.productData); }); }; $scope.$watch('type', function(newValue, oldValue) { if (!newValue) { return; } if(newValue){ $scope._get_product_list_by_category($scope.referral); } }); $scope.shopid = ''; $scope.getShopid = function() { $scope.shopid = CUR_THEME.shop_id(); }; $scope.getShopid(); $scope.initSlider = function() { var elementName = '.row-product[data-id="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, centerMode: true, centerPadding: '0px', slidesToShow: 3, slidesToScroll: 1, dots: false, arrows: false, infinite: true, responsive: [{ breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 2 } }] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(v) { return "-" + ($('.row-product[data-id="' + $scope._uniqueKey + '"]').height() / 2) + v + "px"; }; /* Calculate Product mobile for Arrows */ $scope.calculateProductBlockMobile = function(v) { return $('.row-product[data-id="' + $scope._uniqueKey + '"]').height() / 2; }; $rootScope.$on('repeatend', function() { if ($scope.use_carousel) { var t = $interval(function() { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function() { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); } }); $scope.checkHideCondition = function(referral_id) { return true; if ($location.path() != '/' && $location.path() !== '/home') { if (typeof $routeParams.root_id !== 'undefined' && $routeParams.root_id > 0 && $routeParams.root_id != referral_id) { return false; /* hide */ } return true; } return true; }; }; return promise; });_ui_share_app.factory('$componentProductListBadge', function componentProductListBadge($routeParams, $timeout) { return });_ui_share_app.directive('componentProductListBadgeIdA', function($rootScope, $routeParams) { var templateName = 'componentProductListBadgeIdA'; var componentMain = 'componentProductListBadge'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data_per_page = 15; $scope.JsonDATA = { result_rows: 0, total_rows: 0 }; $scope.JsonProductArray = []; $scope.JsonProductArrayState = { load: false, done: false }; $scope.getJsonProductArray = function(page, id) { $scope.JsonProductArrayState = $scope.StateData(true, false); var dataSend = { 'cur_page': 1, 'per_page': page, 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18, id] }) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope.JsonProductArray = output.data; } $scope.JsonProductArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.getJsonProductArray($scope.data_per_page, $scope._viewRouteParams().badge_id); $scope.loadMore = function() { $scope.data_per_page = parseInt($scope.data_per_page) + 8; $scope.getJsonProductArray($scope.data_per_page, $scope._viewRouteParams().badge_id); }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; }); if (typeof $productTimingRequest == 'undefined') { var $productTimingRequest = { request: 0, data: 0, timeMemory: null, checkAllDone: function () { console.log("checkAllDone", this.data, this.request); if (this.data > 0 && this.data >= this.request) { $('.all-load').addClass('active'); $('.all-content').addClass('active'); this.timeMemory = setTimeout(function () { $('.all-content').addClass('shown'); window.clearTimeout(this.timeMemory); }, 650); } }, instantDisplay: function () { console.log("checkAllDone: not match => display"); $('.all-load').addClass('active'); $('.all-content').addClass('active'); $('.all-content').addClass('shown'); this.timeMemory = null; } }; } var _countHide = 0; _ui_share_app.directive('componentProductRelate', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelate'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', tagname: '@tagname', imgpath: '@imgpath', request: '@type', carousel: '@carousel', referral: '@referral', datapid:'@datapid', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_second': '?textSecond', }; promise.link = function (scope, element, attr) {}; promise.controller = function ($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.forbidden = false; $scope._config = []; $scope._host = _ui_share_host + templateName + '/'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.use_carousel = (typeof $scope.carousel !== 'undefined' && $scope.carousel == 'true') ? true : false; console.log("tagname : ",$scope.tagname); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.productData = []; $scope.productDataload = false; $scope.type = $scope.request; /* GET product list in category (feature *any) */ /* GET product list by badge id (reccommend,new arriaval, best seller, feature) */ /* GET product list by each category (1st level) */ $scope._get_product_list_by_category = function () { $scope.productDataload = false; $productTimingRequest.request = $productTimingRequest.request + 1; var j = { 'badge_id_array': [18], 'tags': $scope.tagname, }; var d = { 'cur_page': 1, 'per_page': 30, 'txt_filter_json': JSON.stringify(j) }; /* root_category_index_asc */ console.log("Fetching 1", $scope.tagname); GAEAPI.get('product/lists', d, $scope).then(function (e) { $scope.productDataload = true; if($scope.datapid != undefined){ for (var i = 0; i < e.data.dataList.length; i++) { if(e.data.dataList[i].product_id != datapid){ $scope.productData.push(e.data.dataList[i]); } } }else{ $scope.productData = e.data.dataList; } $productTimingRequest.data = $productTimingRequest.data + 1; $productTimingRequest.checkAllDone(); if (e.data.dataList.length <= 0 && $routeParams.referral_id == referral_id) { /*window.location.href="home"; */ } else if (e.data.dataList.length <= 0) { $('div[data-id="' + $scope.referral + '"]').hide(); } console.log("Fetching 2", $scope.referral, " : result :", $scope.productData); }); }; $scope.$watch("tagname",function(newValue){ if(GAEAPI.getValue(newValue,"")!=""){ $scope._get_product_list_by_category(); } }); $scope._makeProductToCarousel = function () { var elementName = '[data-id="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 4, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, responsive: [ { breakpoint: 991, settings: { slidesToShow: 3, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 2, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false } } ] }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function (v) { console.log("eeeeeeeeeeeee",("-"+($('.row-product[data-id="' + $scope._uniqueKey + '"]').height()/2))+"px"); return ("-"+(($('.row-product[data-id="' + $scope._uniqueKey + '"]').height()/2)+40))+"px"; }; /* Calculate Product mobile for Arrows */ $scope.calculateProductBlockMobile = function (v) { return $('.row-product[data-id="' + $scope._uniqueKey + '"]').height() / 2; }; $rootScope.$on('repeatend', function () { if ($('[data-id="' + $scope._uniqueKey + '"]').not('.slick-initialized') && $scope.use_carousel) { $timeout(function () { $scope._makeProductToCarousel(); }, 500); } }); $scope.checkHideCondition = function (referral_id) { return true; if ($location.path() != '/' && $location.path() !== '/home') { if (typeof $routeParams.root_id !== 'undefined' && $routeParams.root_id > 0 && $routeParams.root_id != referral_id) { return false; /* hide */ } return true; } return true; }; }; return promise; }); _ui_share_app.directive('componentProductRelateB', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', tagname: '@tagname', stylebutton: '@stylebutton', productid: '@productid', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_second': '?textSecond', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.slideProductDeal = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.productLists = []; $scope.productLists_temp = []; $scope.productListsState = { load: true, done: false }; $scope.getProductLists = function() { $scope.productListsState = $scope.StateData(true, false); var data = { 'badge_id_array': [18], 'tags': $scope.tagname, }; var dataSend = { 'cur_page': 1, 'per_page': 30, 'txt_filter_json': JSON.stringify(data) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { if($scope.productid != undefined){ for (var i = 0; i < output.data.dataList.length; i++) { if(output.data.dataList[i].product_id != $scope.productid){ $scope.productLists.push(output.data.dataList[i]); } } console.log("product relate is id :", $scope.productid , $scope.productLists); }else{ $scope.productLists = output.data.dataList; console.log("product relate is id 2 :", $scope.productid); } } $scope.productListsState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getProductLists(); $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductRelateC', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', tagnameclass: '@tagnameclass', stylebutton: '@stylebutton', productid: '@productid', imgpath : '@imgpath', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_second': '?textSecond', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.slideProductDeal = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.productLists = []; $scope.productLists_temp = []; $scope.productListsState = { load: true, done: false }; $scope.tag_name = []; $scope.getProductLists = function(tagname) { $scope.productListsState = $scope.StateData(true, false); $scope.tag_name = tagname.split(","); console.log("product relate is id 0 :",$scope.tag_name[0]); if($scope.tag_name.length > 1){ var data = { 'badge_id_array': [18], 'tags': ($scope.tagname.split(",").join(",")+""), }; } if($scope.tag_name.length == 1){ var data = { 'badge_id_array': [18], 'tags': $scope.tag_name[0], }; } var dataSend = { 'cur_page': 1, 'per_page': 30, 'txt_filter_json': JSON.stringify(data) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { if($scope.productid != undefined){ for (var i = 0; i < output.data.dataList.length; i++) { if(output.data.dataList[i].product_id != $scope.productid){ $scope.productLists.push(output.data.dataList[i]); } } console.log("product relate is id :", $scope.productid , $scope.productLists , $scope.tag_name.length); }else{ $scope.productLists = output.data.dataList; console.log("product relate is id 2 :", $scope.productid); } } $scope.productListsState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.$watch('tagnameclass', function(newValue, oldValue) { if(newValue){ $scope.getProductLists(newValue); } if (!newValue) return; }); $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductRelateD', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', component: '@component', referralid: '@referralid', stylebutton: '@stylebutton', productid: '@productid', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_second': '?textSecond', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.slideProductDeal = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.productLists = []; $scope.productLists_temp = []; $scope.productListsState = { load: true, done: false }; $scope.getProductLists = function() { $scope.productListsState = $scope.StateData(true, false); var data = { 'referral_id_array_in': $scope.referralid, }; var dataSend = { 'cur_page': 1, 'per_page': 10, 'txt_filter_json': JSON.stringify(data) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { if ($scope.productid != undefined) { for (var i = 0; i < output.data.dataList.length; i++) { if (output.data.dataList[i].product_id != $scope.productid) { $scope.productLists.push(output.data.dataList[i]); } } console.log("product relate is id :", $scope.productid, $scope.productLists); } else { $scope.productLists = output.data.dataList; console.log("product relate is id 2 :", $scope.productid); } } $scope.productListsState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getProductLists(); $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentProductRelateE', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', component: '@component', stylebutton: '@stylebutton', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_end': '?textEnd', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { console.log('componentProductRelateE : ', functionName, ' : ', data); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getProductId: function(params, callback) { var _self = this; var product_id = params.product_id.split("-", 1).join(""); _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_api, state); }); }, carousel: function(coverIn, carouselIn) { $(coverIn).css('height', '0'); $(carouselIn).css('opacity', '0'); setTimeout(function() { var carousel = $(carouselIn); carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); $(coverIn).css('height', 'auto'); $(carouselIn).css('opacity', '1'); }, 100); }, getCarousel: function(carousel, callback) { var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, main: function() { var _self = this; } } return getFunction; }; $scope.data = { carousel: 0, arrayState: { load: false, done: false }, ok: true, array: [] }; $scope.getData().getCarousel($scope.data.carousel, function(res_carousel_id) { $scope.data.carousel = res_carousel_id; $scope.getData().getRouteParams(function(res_params, res_state) { $scope.data.arrayState = res_state; $scope.getData().getProductId(res_params, function(res_product_id) { var dataSend = { 'txt_product_id': res_product_id, 'txt_limit': 10, 'jso_badge': JSON.stringify([18]) }; $scope.getData().dataSend('product/related', dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res, res_state) { console.log("getApi + + + + + : dataSend :", dataSend); console.log("getApi + + + + + : res :", res); $scope.data.array = res.data.lists; $scope.data.arrayState = res_state; }); }); }); }); }); }; return promise; });_ui_share_app.directive('componentProductRelateEa', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateEa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productid: '@productid', limit: '@limit', tagname: '@tagname', component: '@component', stylebutton: '@stylebutton', productid: '@productid', margin: '@margin', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_end': '?textEnd', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._idUrl = function(instr) { console.log("_idUrl : ", instr); var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.slideProductDeal = function(elem) { $('.component-product-relate-e').css('height', '0'); $('.component-product-relate-e').css('opacity', '0'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); $('.component-product-relate-e').css('height', 'auto'); $('.component-product-relate-e').css('opacity', '1'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.consoleLog = function(text, data) { console.log(text, ' : ', data); }; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getDataArray = function(id, limit) { $scope.consoleLog('_getDataArray id', id); $scope.consoleLog('_getDataArray limit', limit); $scope._dataArrayState = $scope.StateData(true, false); var data = { 'referral_id_array_in': [$scope.referralid], 'tags': $scope.tagname }; var dataSend = { 'txt_product_id': id, 'txt_limit': limit, }; $scope.consoleLog('_getDataArray dataSend', dataSend); GAEAPI.get('product/related', dataSend, $scope).then(function(output) { $scope.consoleLog('_getDataArray output', output); if (output.ok == 1) { $scope._dataArray = output.data.lists; $scope.consoleLog('_getDataArray _dataArray', $scope._dataArray); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray($scope._idUrl($scope.productid), $scope.limit); }; return promise; });_ui_share_app.directive('componentProductRelateEb', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateEb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referralid: '@referralid', tagname: '@tagname', component: '@component', stylebutton: '@stylebutton', productid: '@productid', margin: '@margin', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_end': '?textEnd', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.slideProductDeal = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var data = { 'referral_id_array_in': [$scope.referralid], 'tags': $scope.tagname }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'txt_filter_json': JSON.stringify(data) }; console.log("estsefrdsgdsfgdfsg", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { if ($scope.productid != undefined) { for (var i = 0; i < output.data.dataList.length; i++) { if (output.data.dataList[i].product_id != $scope.productid) { $scope._dataArray.push(output.data.dataList[i]); } } } else { } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } setTimeout(function() { $scope._getDataArray(); }, 2000); }; return promise; });_ui_share_app.directive('componentProductRelateEg', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateEg'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productid: '@productid', limit: '@limit', tagname: '@tagname', component: '@component', stylebutton: '@stylebutton', margin: '@margin', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_end': '?textEnd', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.slideProductDeal = function(elem) { $('.component-product-relate-e').css('height', '0'); $('.component-product-relate-e').css('opacity', '0'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 3 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); $('.component-product-relate-e').css('height', 'auto'); $('.component-product-relate-e').css('opacity', '1'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.consoleLog = function(text, data) { console.log(text, ' : ', data); }; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getDataArray = function(id, limit) { $scope.consoleLog('_getDataArray id', id); $scope.consoleLog('_getDataArray limit', limit); $scope._dataArrayState = $scope.StateData(true, false); var data = { 'referral_id_array_in': [$scope.referralid], 'tags': $scope.tagname }; var dataSend = { 'txt_product_id': id, 'txt_limit': limit, }; $scope.consoleLog('_getDataArray dataSend', dataSend); GAEAPI.get('product/related', dataSend, $scope).then(function(output) { $scope.consoleLog('_getDataArray output', output); if (output.ok == 1) { // $scope.$apply(function() { $scope._dataArray = output.data.lists; $scope.consoleLog('_getDataArray _dataArray', $scope._dataArray); // }); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.$watch('productid', function (newValue, oldValue) { if (newValue){ $scope._getDataArray($scope.productid, $scope.limit); }else{ return; } }); }; return promise; });_ui_share_app.directive('componentProductRelateF', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referralid: '@referralid', tagname: '@tagname', component: '@component', stylebutton: '@stylebutton', margintopic: '@margintopic', margincard: '@margincard', limitdata: '@limitdata', iconsize: '@iconsize', iconnext: '@iconnext', iconback: '@iconback', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; $scope.productid = $scope._getPostIdFromURL(); $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope.mkCarousel = function(elem) { $('.component-product-relate-f').css('height', '0'); $('.component-product-relate-f').css('opacity', '0'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1200, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 2, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); $('.component-product-relate-f').css('height', 'auto'); $('.component-product-relate-f').css('opacity', '1'); }, 100); }; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function(id, tags) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { 'referral_id_array_in': [id], 'tags': tags } var dataSend = { 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/lists', dataSend).then(function(res) { if (res.ok === 1) { for (var i = 0; i < res.data.dataList.length; i++) { if (res.data.dataList[i].product_id != $scope.productid) { $scope._dataArray.push(res.data.dataList[i]); } } /* $scope._dataArray = res.data.dataList; */ } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.$watch('referralid', function(newValue, oldValue) {             if (!newValue) { return; }              $scope._getProductArray($scope.referralid, $scope.tagname); }); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; }; return promise; });_ui_share_app.directive('componentProductRelateHongmin', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateHongmin'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', referralid: '@referralid', tagname: '@tagname', }; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._component = "componentProductRelateHongmin"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getProductId: function(params, callback) { var _self = this; var product_id = (params.product_id != undefined) ? params.product_id.split("-", 1).join("") : false; _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getReferralId: function(productReferralDisplay, callback) { var _self = this; var referral_id = 0; if (productReferralDisplay.length != 0) { if (productReferralDisplay.category != undefined) { if (productReferralDisplay.category.length != 0) { referral_id = productReferralDisplay.category[0].referral_id } } } callback(referral_id); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getFunctionCarousel: function(callback) { var _self = this; callback(_self); }, setCarousels: function(carousel, callback) { var _self = this; callback(carousel); }, pushObjectCarousel: function(callback) { var _self = this; var objectArray = { speed: 600, dots: false, arrows: false, infinite: false, autoplay: false, focusOnSelect: false, adaptiveHeight: false, autoplaySpeed: 4000, slidesToScroll: 1, centerMode: false, centerPadding: '0px', prevArrow: '', nextArrow: '' }; $scope.carousels.push(objectArray); var res_index = ($scope.carousels.length != 0) ? $scope.carousels.length - 1 : 0; callback(res_index); }, setSpeed: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.speed = state; }); }, setDots: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.dots = state; }); }, setArrows: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.arrows = state; }); }, setInfinite: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.infinite = state; }); }, setAutoplay: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.autoplay = state; }); }, setAdaptiveHeight: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.adaptiveHeight = state; }); }, setAutoplaySpeed: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.autoplaySpeed = state; }); }, setCenterMode: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.centerMode = state; }); }, setCenterPadding: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.centerPadding = state; }); }, setFocusOnSelect: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.focusOnSelect = state; }); }, setSlidesToScroll: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.slidesToScroll = state; }); }, setPrevArrow: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.prevArrow = state; }); }, setNextArrow: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.nextArrow = state; }); }, getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carousel: function(cover, carousel, xs, sm, md, lg) { var _self = this; var carousels = $(carousel); $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); var _xs = parseInt(xs); var _sm = parseInt(sm); var _md = parseInt(md); var _lg = parseInt(lg); setTimeout(function() { carousels.not('.slick-initialized').slick({ speed: $scope.carousels[0].speed, dots: $scope.carousels[0].dots, arrows: $scope.carousels[0].arrows, infinite: $scope.carousels[0].infinite, autoplay: $scope.carousels[0].autoplay, slidesToScroll: $scope.carousels[0].slidesToScroll, slidesToShow: _lg, autoplaySpeed: $scope.carousels[0].autoplaySpeed, adaptiveHeight: $scope.carousels[0].adaptiveHeight, prevArrow: $scope.carousels[0].prevArrow, nextArrow: $scope.carousels[0].nextArrow, responsive: [{ breakpoint: 1200, settings: { slidesToShow: _md, } }, { breakpoint: 991, settings: { slidesToShow: _sm, } }, { breakpoint: 767, settings: { slidesToShow: _xs, } }], }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselIndex: function(index, cover, carousel, xs, sm, md, lg) { var _self = this; var carousels = $(carousel); $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); var _xs = parseInt(xs); var _sm = parseInt(sm); var _md = parseInt(md); var _lg = parseInt(lg); var slick_array = {}; slick_array.slidesToShow = _lg; slick_array.arrows = $scope.carousels[index].arrows; if ($scope.carousels[index].dots) { slick_array.dots = $scope.carousels[index].dots; } if ($scope.carousels[index].speed != 0) { slick_array.speed = $scope.carousels[index].speed; } if ($scope.carousels[index].autoplay) { slick_array.arrows = $scope.carousels[index].arrows; } if ($scope.carousels[index].infinite) { slick_array.infinite = $scope.carousels[index].infinite; } if ($scope.carousels[index].prevArrow != '') { slick_array.prevArrow = $scope.carousels[index].prevArrow; } if ($scope.carousels[index].nextArrow != '') { slick_array.nextArrow = $scope.carousels[index].nextArrow; } if ($scope.carousels[index].centerMode) { slick_array.centerMode = $scope.carousels[index].centerMode; } if ($scope.carousels[index].centerPadding != '0' && $scope.carousels[index].centerPadding != '') { slick_array.centerPadding = $scope.carousels[index].centerPadding; } if ($scope.carousels[index].focusOnSelect) { slick_array.focusOnSelect = $scope.carousels[index].focusOnSelect; } if ($scope.carousels[index].autoplaySpeed != 0) { slick_array.autoplaySpeed = $scope.carousels[index].autoplaySpeed; } if ($scope.carousels[index].adaptiveHeight) { slick_array.adaptiveHeight = $scope.carousels[index].adaptiveHeight; } if ($scope.carousels[index].slidesToScroll != 0) { slick_array.slidesToScroll = $scope.carousels[index].slidesToScroll; } slick_array.responsive = [{ breakpoint: 1200, settings: { slidesToShow: _md, } }, { breakpoint: 991, settings: { slidesToShow: _sm, } }, { breakpoint: 767, settings: { slidesToShow: _xs, } }]; if ($scope.carousels[index].centerPadding != '0' && $scope.carousels[index].centerPadding != '') { slick_array.centerPadding = $scope.carousels[index].centerPadding; slick_array.responsive[2].settings.centerPadding = '0px' } setTimeout(function() { carousels.not('.slick-initialized').slick(slick_array).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 1000); } } return getFunction; }; $scope.carousels = [{ speed: 600, dots: false, arrows: true, infinite: true, autoplay: true, adaptiveHeight: true, autoplaySpeed: 4000, slidesToScroll: 1, prevArrow: '', nextArrow: '' }]; $scope.dataApi = { related: { dataSend: {}, api: "product/lists", ok: false, dataArray: [], dataArrayState: { load: false, done: false } } }; $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.related.dataArrayState = res_state; $scope.getData().getProductId(res_params, function(res_product_id) { var filter_json = { 'referral_id_array_in': [$scope.referralid], 'tags': $scope.tagname }; var dataSend = { 'cur_page': 1, 'per_page': 12, 'jso_badge': JSON.stringify(filter_json) }; $scope.dataApi.related.dataSend = dataSend; $scope.getData().dataSend($scope.dataApi.related.api, $scope.dataApi.related.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_related, res_state) { $scope.dataApi.related.ok = res_ok; $scope.dataApi.related.dataArray = get_res_api_related.data.dataList; $scope.getData().consoleLog("get_res_api_big_related", get_res_api_related); $scope.dataApi.related.dataArrayState = res_state; }); }); }); }); }; return promise; });_ui_share_app.directive('componentProductRelateMagic', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateMagic'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._component = "componentProductRelateMagic"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(_self,params, state); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, getProductId: function(params, callback) { var _self = this; var product_id = (params.product_id != undefined) ? params.product_id.split("-", 1).join("") : false; _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getReferralId: function(productReferralDisplay, callback) { var _self = this; var referral_id = 0; if (productReferralDisplay.length != 0) { if (productReferralDisplay.category != undefined) { if (productReferralDisplay.category.length != 0) { referral_id = productReferralDisplay.category[0].referral_id } } } callback(referral_id); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getFunctionCarousel: function(callback) { var _self = this; callback(_self); }, setCarousels: function(carousel, callback) { var _self = this; callback(carousel); }, pushObjectCarousel: function(callback) { var _self = this; var objectArray = { speed: 600, dots: false, arrows: false, infinite: false, autoplay: false, focusOnSelect: false, adaptiveHeight: false, autoplaySpeed: 4000, slidesToScroll: 1, centerMode: false, centerPadding: '0px', prevArrow: '', nextArrow: '' }; $scope.carousels.push(objectArray); var res_index = ($scope.carousels.length != 0) ? $scope.carousels.length - 1 : 0; callback(res_index); }, setSpeed: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.speed = state; }); }, setDots: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.dots = state; }); }, setArrows: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.arrows = state; }); }, setInfinite: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.infinite = state; }); }, setAutoplay: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.autoplay = state; }); }, setAdaptiveHeight: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.adaptiveHeight = state; }); }, setAutoplaySpeed: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.autoplaySpeed = state; }); }, setCenterMode: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.centerMode = state; }); }, setCenterPadding: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.centerPadding = state; }); }, setFocusOnSelect: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.focusOnSelect = state; }); }, setSlidesToScroll: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.slidesToScroll = state; }); }, setPrevArrow: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.prevArrow = state; }); }, setNextArrow: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.nextArrow = state; }); }, getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carousel: function(cover, carousel, xs, sm, md, lg) { var _self = this; var carousels = $(carousel); $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); var _xs = parseInt(xs); var _sm = parseInt(sm); var _md = parseInt(md); var _lg = parseInt(lg); setTimeout(function() { carousels.not('.slick-initialized').slick({ speed: $scope.carousels[0].speed, dots: $scope.carousels[0].dots, arrows: $scope.carousels[0].arrows, infinite: $scope.carousels[0].infinite, autoplay: $scope.carousels[0].autoplay, slidesToScroll: $scope.carousels[0].slidesToScroll, slidesToShow: _lg, autoplaySpeed: $scope.carousels[0].autoplaySpeed, adaptiveHeight: $scope.carousels[0].adaptiveHeight, prevArrow: $scope.carousels[0].prevArrow, nextArrow: $scope.carousels[0].nextArrow, responsive: [{ breakpoint: 1200, settings: { slidesToShow: _md, } }, { breakpoint: 991, settings: { slidesToShow: _sm, } }, { breakpoint: 767, settings: { slidesToShow: _xs, } }], }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselIndex: function(index, cover, carousel, xs, sm, md, lg) { var _self = this; var carousels = $(carousel); $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); var _xs = parseInt(xs); var _sm = parseInt(sm); var _md = parseInt(md); var _lg = parseInt(lg); var slick_array = {}; slick_array.slidesToShow = _lg; slick_array.arrows = $scope.carousels[index].arrows; if ($scope.carousels[index].dots) { slick_array.dots = $scope.carousels[index].dots; } if ($scope.carousels[index].speed != 0) { slick_array.speed = $scope.carousels[index].speed; } if ($scope.carousels[index].autoplay) { slick_array.arrows = $scope.carousels[index].arrows; } if ($scope.carousels[index].infinite) { slick_array.infinite = $scope.carousels[index].infinite; } if ($scope.carousels[index].prevArrow != '') { slick_array.prevArrow = $scope.carousels[index].prevArrow; } if ($scope.carousels[index].nextArrow != '') { slick_array.nextArrow = $scope.carousels[index].nextArrow; } if ($scope.carousels[index].centerMode) { slick_array.centerMode = $scope.carousels[index].centerMode; } if ($scope.carousels[index].centerPadding != '0' && $scope.carousels[index].centerPadding != '') { slick_array.centerPadding = $scope.carousels[index].centerPadding; } if ($scope.carousels[index].focusOnSelect) { slick_array.focusOnSelect = $scope.carousels[index].focusOnSelect; } if ($scope.carousels[index].autoplaySpeed != 0) { slick_array.autoplaySpeed = $scope.carousels[index].autoplaySpeed; } if ($scope.carousels[index].adaptiveHeight) { slick_array.adaptiveHeight = $scope.carousels[index].adaptiveHeight; } if ($scope.carousels[index].slidesToScroll != 0) { slick_array.slidesToScroll = $scope.carousels[index].slidesToScroll; } slick_array.responsive = [{ breakpoint: 1200, settings: { slidesToShow: _md, } }, { breakpoint: 991, settings: { slidesToShow: _sm, } }, { breakpoint: 767, settings: { slidesToShow: _xs, } }]; if ($scope.carousels[index].centerPadding != '0' && $scope.carousels[index].centerPadding != '') { slick_array.centerPadding = $scope.carousels[index].centerPadding; slick_array.responsive[2].settings.centerPadding = '0px' } setTimeout(function() { carousels.not('.slick-initialized').slick(slick_array).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 1000); } } return getFunction; }; $scope.carousels = [{ speed: 600, dots: false, arrows: false, infinite: true, autoplay: true, adaptiveHeight: true, autoplaySpeed: 4000, slidesToScroll: 1, prevArrow: '', nextArrow: '' }]; $scope.dataApi = { shop_current: { data_send: {}, api: "shop/current", ok: false, data_array: [], data_array_state: { load: false, done: false } }, related: { dataSend: {}, api: "product/big_related", ok: false, dataArray: [], dataArrayState: { load: false, done: false } } }; $scope.getData().getRouteParams(function(_self,res_params, res_state) { $scope.dataApi.shop_current.data_array_state = res_state; _self.formatDataSend($scope.dataApi.shop_current, function(res_data) { _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); $scope.dataApi.related.dataArrayState = res_state; $scope.getData().getProductId(res_params, function(res_product_id) { var filter_json = [18]; var dataSend = { 'txt_product_id': res_product_id, 'cur_page': 1, 'per_page': 12, 'jso_badge': JSON.stringify(filter_json) }; $scope.dataApi.related.dataSend = dataSend; $scope.getData().dataSend($scope.dataApi.related.api, $scope.dataApi.related.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_related, res_state) { $scope.dataApi.related.ok = res_ok; /* angular.forEach(get_res_api_related.data.dataList, function(item, index) { $scope.getData().getNameUrl(get_res_api_related.data.dataList[index].product_title, function(res_title) { get_res_api_related.data.dataList[index].product_title_url = res_title; }); var images = []; angular.forEach(item.product_image,function(image,index_image){ if (image.image_app_cover_checked) { images.push(image) } }); item.product_image = images; }); */ $scope.dataApi.related.dataArray = get_res_api_related.data.dataList; $scope.getData().consoleLog("get_res_api_big_related", get_res_api_related); }); }); }); }); }; return promise; });_ui_share_app.directive('componentProductRelateVono', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductRelateVono'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._component = "componentProductRelateVono"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, getProductId: function(params, callback) { var _self = this; var product_id = (params.product_id != undefined) ? params.product_id.split("-", 1).join("") : false; _self.consoleLog("getProductId product_id", product_id); callback(product_id); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, getReferralId: function(productReferralDisplay, callback) { var _self = this; var referral_id = 0; if (productReferralDisplay.length != 0) { if (productReferralDisplay.category != undefined) { if (productReferralDisplay.category.length != 0) { referral_id = productReferralDisplay.category[0].referral_id } } } callback(referral_id); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.getCarousel = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._console) { console.log($scope._component, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getFunctionCarousel: function(callback) { var _self = this; callback(_self); }, setCarousels: function(carousel, callback) { var _self = this; callback(carousel); }, pushObjectCarousel: function(callback) { var _self = this; var objectArray = { speed: 600, dots: false, arrows: false, infinite: false, autoplay: false, focusOnSelect: false, adaptiveHeight: false, autoplaySpeed: 4000, slidesToScroll: 1, centerMode: false, centerPadding: '0px', prevArrow: '', nextArrow: '' }; $scope.carousels.push(objectArray); var res_index = ($scope.carousels.length != 0) ? $scope.carousels.length - 1 : 0; callback(res_index); }, setSpeed: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.speed = state; }); }, setDots: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.dots = state; }); }, setArrows: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.arrows = state; }); }, setInfinite: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.infinite = state; }); }, setAutoplay: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.autoplay = state; }); }, setAdaptiveHeight: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.adaptiveHeight = state; }); }, setAutoplaySpeed: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.autoplaySpeed = state; }); }, setCenterMode: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.centerMode = state; }); }, setCenterPadding: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.centerPadding = state; }); }, setFocusOnSelect: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.focusOnSelect = state; }); }, setSlidesToScroll: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.slidesToScroll = state; }); }, setPrevArrow: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.prevArrow = state; }); }, setNextArrow: function(index, state) { var _self = this; _self.setCarousels($scope.carousels[index], function(res_carousel) { res_carousel.nextArrow = state; }); }, getCarousel: function(carousel, callback) { var _self = this; var carousel_id = 0; if (carousel == 0) { carousel_id = Math.floor((Math.random() * 9999) + 1000); } callback(carousel_id); }, carousel: function(cover, carousel, xs, sm, md, lg) { var _self = this; var carousels = $(carousel); $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); var _xs = parseInt(xs); var _sm = parseInt(sm); var _md = parseInt(md); var _lg = parseInt(lg); setTimeout(function() { carousels.not('.slick-initialized').slick({ speed: $scope.carousels[0].speed, dots: $scope.carousels[0].dots, arrows: $scope.carousels[0].arrows, infinite: $scope.carousels[0].infinite, autoplay: $scope.carousels[0].autoplay, slidesToScroll: $scope.carousels[0].slidesToScroll, slidesToShow: _lg, autoplaySpeed: $scope.carousels[0].autoplaySpeed, adaptiveHeight: $scope.carousels[0].adaptiveHeight, prevArrow: $scope.carousels[0].prevArrow, nextArrow: $scope.carousels[0].nextArrow, responsive: [{ breakpoint: 1200, settings: { slidesToShow: _md, } }, { breakpoint: 991, settings: { slidesToShow: _sm, } }, { breakpoint: 767, settings: { slidesToShow: _xs, } }], }).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 500); }, carouselIndex: function(index, cover, carousel, xs, sm, md, lg) { var _self = this; var carousels = $(carousel); $(cover).css('height', '0'); $(cover).css('opacity', '0'); $(carousel).css('opacity', '0'); var _xs = parseInt(xs); var _sm = parseInt(sm); var _md = parseInt(md); var _lg = parseInt(lg); var slick_array = {}; slick_array.slidesToShow = _lg; slick_array.arrows = $scope.carousels[index].arrows; if ($scope.carousels[index].dots) { slick_array.dots = $scope.carousels[index].dots; } if ($scope.carousels[index].speed != 0) { slick_array.speed = $scope.carousels[index].speed; } if ($scope.carousels[index].autoplay) { slick_array.arrows = $scope.carousels[index].arrows; } if ($scope.carousels[index].infinite) { slick_array.infinite = $scope.carousels[index].infinite; } if ($scope.carousels[index].prevArrow != '') { slick_array.prevArrow = $scope.carousels[index].prevArrow; } if ($scope.carousels[index].nextArrow != '') { slick_array.nextArrow = $scope.carousels[index].nextArrow; } if ($scope.carousels[index].centerMode) { slick_array.centerMode = $scope.carousels[index].centerMode; } if ($scope.carousels[index].centerPadding != '0' && $scope.carousels[index].centerPadding != '') { slick_array.centerPadding = $scope.carousels[index].centerPadding; } if ($scope.carousels[index].focusOnSelect) { slick_array.focusOnSelect = $scope.carousels[index].focusOnSelect; } if ($scope.carousels[index].autoplaySpeed != 0) { slick_array.autoplaySpeed = $scope.carousels[index].autoplaySpeed; } if ($scope.carousels[index].adaptiveHeight) { slick_array.adaptiveHeight = $scope.carousels[index].adaptiveHeight; } if ($scope.carousels[index].slidesToScroll != 0) { slick_array.slidesToScroll = $scope.carousels[index].slidesToScroll; } slick_array.responsive = [{ breakpoint: 1200, settings: { slidesToShow: _md, } }, { breakpoint: 991, settings: { slidesToShow: _sm, } }, { breakpoint: 767, settings: { slidesToShow: _xs, } }]; if ($scope.carousels[index].centerPadding != '0' && $scope.carousels[index].centerPadding != '') { slick_array.centerPadding = $scope.carousels[index].centerPadding; slick_array.responsive[2].settings.centerPadding = '0px' } setTimeout(function() { carousels.not('.slick-initialized').slick(slick_array).closest('section').addClass('active'); $(cover).css('height', 'auto'); $(cover).css('opacity', '1'); $(carousel).css('opacity', '1'); }, 1000); } } return getFunction; }; $scope.carousels = [{ speed: 600, dots: false, arrows: false, infinite: true, autoplay: true, adaptiveHeight: true, autoplaySpeed: 4000, slidesToScroll: 1, prevArrow: '', nextArrow: '' }]; $scope.dataApi = { related: { dataSend: {}, api: "product/big_related", ok: false, dataArray: [], dataArrayState: { load: false, done: false } } }; $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.related.dataArrayState = res_state; $scope.getData().getProductId(res_params, function(res_product_id) { var filter_json = [18]; var dataSend = { 'txt_product_id': res_product_id, 'cur_page': 1, 'per_page': 12, 'jso_badge': JSON.stringify(filter_json) }; $scope.dataApi.related.dataSend = dataSend; $scope.getData().dataSend($scope.dataApi.related.api, $scope.dataApi.related.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_related, res_state) { $scope.dataApi.related.ok = res_ok; angular.forEach(get_res_api_related.data.dataList, function(item, index) { $scope.getData().getNameUrl(get_res_api_related.data.dataList[index].product_title, function(res_title) { get_res_api_related.data.dataList[index].product_title_url = res_title; }); var images = []; angular.forEach(item.product_image,function(image,index_image){ if (image.image_app_cover_checked) { images.push(image) } }); item.product_image = images; }); $scope.dataApi.related.dataArray = get_res_api_related.data.dataList; $scope.getData().consoleLog("get_res_api_big_related", get_res_api_related); }); }); }); }); }; return promise; });_ui_share_app.directive('componentProductReward', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentProductReward'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productid: '@productid', qty: '@qty', pricesale: '@pricesale', imgreward: '@imgreward', textright: '@textright', textbefore: '@textbefore', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._dataArray = false; $scope.reward = false; $scope.qty = $scope.qty || 1; $scope.rewardlast = 0; $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; $scope.$watch('productid', function(newValue, oldValue) { if (newValue) { $scope._getDataArray(newValue); } else { return; } }); $scope.$watch('pricesale', function(newValue, oldValue) { if (newValue) { if ($scope._dataArray.product_reward != undefined) { if ($scope._dataArray.product_reward.reward_type_id == 103) { if (($scope.qty * newValue) % $scope._dataArray.product_reward.reward_every_price == 0) { $scope.pointmain = ($scope.qty * newValue / $scope._dataArray.product_reward.reward_every_price) * $scope._dataArray.product_reward.reward_amount; $scope.rewardTime($scope._dataArray.product_reward.reward_lifetime.lifetime_start_time, $scope._dataArray.product_reward.reward_lifetime.lifetime_end_time, $scope.pointmain); } else { var price_all = ($scope.qty * newValue) - (($scope.qty * newValue) % $scope._dataArray.product_reward.reward_every_price); $scope.pointmain = (price_all / $scope._dataArray.product_reward.reward_every_price) * $scope._dataArray.product_reward.reward_amount; $scope.rewardTime($scope._dataArray.product_reward.reward_lifetime.lifetime_start_time, $scope._dataArray.product_reward.reward_lifetime.lifetime_end_time, $scope.pointmain); } } else if ($scope._dataArray.product_reward.reward_type_id == 102) { $scope.pointmain = ($scope._dataArray.product_reward.reward_percent / 100) * ($scope.qty * newValue); $scope.rewardTime($scope._dataArray.product_reward.reward_lifetime.lifetime_start_time, $scope._dataArray.product_reward.reward_lifetime.lifetime_end_time, $scope.pointmain); } else { $scope.rewardlast = $scope.getreward($scope.qty); } } } else { $scope.rewardlast = $scope.getreward(1); } }); $scope.$watch('qty', function(newValue, oldValue) { if (newValue) { if ($scope._dataArray.product_reward != undefined) { if ($scope._dataArray.product_reward.reward_type_id == 103) { if (($scope.pricesale * newValue) % $scope._dataArray.product_reward.reward_every_price == 0) { $scope.pointmain = ($scope.pricesale * newValue / $scope._dataArray.product_reward.reward_every_price) * $scope._dataArray.product_reward.reward_amount; $scope.rewardTime($scope._dataArray.product_reward.reward_lifetime.lifetime_start_time, $scope._dataArray.product_reward.reward_lifetime.lifetime_end_time, $scope.pointmain); } else { var price_all = ($scope.pricesale * newValue) - (($scope.pricesale * newValue) % $scope._dataArray.product_reward.reward_every_price); $scope.pointmain = (price_all / $scope._dataArray.product_reward.reward_every_price) * $scope._dataArray.product_reward.reward_amount; $scope.rewardTime($scope._dataArray.product_reward.reward_lifetime.lifetime_start_time, $scope._dataArray.product_reward.reward_lifetime.lifetime_end_time, $scope.pointmain); } } else if ($scope._dataArray.product_reward.reward_type_id == 102) { $scope.pointmain = ($scope._dataArray.product_reward.reward_percent / 100) * ($scope.pricesale * newValue); $scope.rewardTime($scope._dataArray.product_reward.reward_lifetime.lifetime_start_time, $scope._dataArray.product_reward.reward_lifetime.lifetime_end_time, $scope.pointmain); } else { $scope.rewardlast = $scope.getreward(newValue); } } } else { $scope.rewardlast = $scope.getreward(1); } }); $scope.pointmain = 0; $scope._getDataArray = function(id) { $scope.pointmain = 0; $scope.reward = false; var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend, $scope).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; if ($scope._dataArray.product_reward.length != 0) { var starttime = $scope._dataArray.product_reward.reward_lifetime.lifetime_start_time; var endtime = $scope._dataArray.product_reward.reward_lifetime.lifetime_end_time; if ($scope._dataArray.product_reward.reward_type_id == 101) { $scope.pointmain = $scope._dataArray.product_reward.reward_amount; $scope.rewardTime(starttime, endtime, $scope.pointmain); } if ($scope._dataArray.product_reward.reward_type_id == 102) { $scope.pointmain = ($scope._dataArray.product_reward.reward_percent / 100) * $scope.pricesale; $scope.rewardTime(starttime, endtime, $scope.pointmain); } if ($scope._dataArray.product_reward.reward_type_id == 103) { $scope.pointmain = ($scope.pricesale * $scope.qty / $scope._dataArray.product_reward.reward_every_price) * $scope._dataArray.product_reward.reward_amount; /* if($scope.pointmain%$scope._dataArray.product_reward.reward_amount == 0){ } */ if ($scope.pointmain >= $scope._dataArray.product_reward.reward_amount) { /* alert($scope.pointmain); */ $scope.rewardTime(starttime, endtime, $scope.pointmain); } else { $scope.popkaisod = true; } } } } }); }; $scope.rewardTime = function(t_start, t_end, reward_point) { console.log("rewardTime : reward_point : ", reward_point, " t_start : ", parseInt(t_start), " t_end : ", parseInt(t_end)); var date_now = new Date(); var date_start = new Date(t_start * 1000); var date_end = new Date(t_end * 1000); console.log("rewardTime : date_now : ", date_now, " date_end : ", date_end, " date_start : ", date_start); if (parseInt(t_start) <= parseInt(t_end)) { if (date_start <= date_now && date_end > date_now) { $scope.reward = reward_point; $scope.rewardlast = $scope.reward; } } else if (parseInt(t_end) == -1) { $scope.reward = reward_point; $scope.rewardlast = $scope.reward; } else { if (parseInt(t_start) <= date_now && parseInt(t_end) > date_now) { $scope.reward = reward_point; $scope.rewardlast = $scope.reward; } } /* var date_end = 0; var date_now = new Date(); var date_start = new Date(t_start * 1000); if (t_end != -1) { date_end = new Date(t_end * 1000); if (t_start <= date_now && t_end > date_now) { $scope.reward = reward_point; $scope.rewardlast = $scope.reward; } } if (t_start <= date_now && t_end == -1) { $scope.reward = reward_point; $scope.rewardlast = $scope.reward; console.log("point_reward 3 :", $scope.reward); } */ }; $scope.getreward = function(valuer) { return $scope.reward * valuer; } }; return promise; });_ui_share_app.factory('$componentProductSetDetail', function componentProductSetDetail($routeParams, $timeout) { return });_ui_share_app.directive('componentProductSetDetailTypeA', function($rootScope, $routeParams) { var templateName = 'componentProductSetDetailTypeA'; var componentMain = 'componentProductSetDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', promotelink: '@promotelink', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataTag = false; $scope._dataArray = []; $scope.product_sku = ""; $scope.product_code = ""; $scope.product_price = 0; $scope.product_compare_price = 0; $scope._dataArrayState = { load: true, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/set_id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; console.log("_getDataArray _dataArray : ", $scope._dataArray); $scope.dataPreserve = res.data; if (res.data.product_sku != undefined) { $scope.product_sku = res.data.product_sku; } if (res.data.product_code != undefined) { $scope.product_code = res.data.product_code; } $scope.product_price = res.data.product_price; /*$scope.calculate( res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent);*/ if (res.data.product_tag != undefined) { $scope.dataTag = res.data.product_tags.split(","); } $scope.qtyCurrentSize(0, 20); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.mkCarousel = function(elem) { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { slidesToShow: 1, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.dataRelation = []; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getIdUrl = function() { var getData = []; var returnData = ''; if (typeof $routeParams.product_id !== 'undefined') { getData = $routeParams.product_id; returnData = getData.split("-"); return returnData[0]; } }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleStatres.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleStatres.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.qtyCurrentSize = function(product_total_variant, product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : product_total_variant : ", product_total_variant, "product_total_stock : ", product_total_stock); if (product_total_variant == 0) { if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < parseInt(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock < 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock == 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else { $scope.qty_current_size_state = false; $scope.buy_state = false; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_variant > 0) { if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < product_total_stock; i++) { $scope.qty_current_size.push(i + 1); } } } $scope.qtyShow($scope.qty_current_size); }; $scope.htmlSelectTime = 0; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } } $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").val() == undefined) { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); check_int = 1; } else if ($(".d_qty").val() == "? number:1 ?") { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); } else { check_int = parseInt($(".d_qty").val()); $(".d_qty").val(check_int); } return check_int; }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems option_id:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems dataVariantsPick:", $scope.dataVariantsPick); }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); console.log("dataVariants :", dataVariants); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_qๆid = dataVariants[i].product_id; if (dataVariants[i].sku != "") { $scope.product_sku = dataVariants[i].sku; } else { $scope.product_sku = $scope._dataArray.product_sku; } if (dataVariants[i].sku != "") { $scope.product_code = dataVariants[i].barcode; } else { $scope.product_code = $scope._dataArray.product_code; } $scope.product_price = $scope.calculate(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); break; } else { $scope.qty_current_size_state = false; $scope.buy_state = false; $scope.product_price = $scope._dataArray.product_price; $scope.product_compare_price = $scope._dataArray.product_compare_price; $scope.product_sku = $scope._dataArray.product_sku; $scope.product_code = $scope._dataArray.product_code; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope._getDataArray($scope._getIdUrl()); $scope.returnSizeProductCard = function() { var id = $("#productcard"); var out = $("#productcard_product_title"); return id.outerHeight(); }; $scope.checkHide = function() { var start = 8; var end = 23; var DateHours = (new Date()).getHours(); return [23, 0, 1, 2, 3, 4, 5, 6, 7].indexOf(DateHours) != -1; }; }; return promise; });_ui_share_app.directive('componentProductSetDetailTypeB', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductSetDetailTypeB'; var componentMain = 'componentProductSetDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataTag = false; $scope._dataArray = []; $scope.product_id = ""; $scope.product_sku = ""; $scope.product_code = ""; $scope.product_price = 0; $scope.product_compare_price = 0; // $scope.promotion_list = 0; $scope._dataArrayState = { load: true, done: false }; // console.log("promotion_list : ", $scope.promotion_list); $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'txt_product_id': id, }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/set_id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; // if($scope._dataArray.product_is_promotion != 0){ // $scope.promotion_list = $scope._dataArray.product_promotion[0].promotion_id; // } // console.log("promotion_list : ", $scope.promotion_list); console.log("_getDataArray _dataArray : ", $scope._dataArray); $scope.product_id = $scope._dataArray.product_id; $scope.dataPreserve = res.data; if (res.data.product_sku != undefined) { $scope.product_sku = res.data.product_sku; } if (res.data.product_code != undefined) { $scope.product_code = res.data.product_code; } $scope.product_price = $scope.calculate(res.data.product_set_price.original_price,res.data.product_price, res.data.product_compare_price, res.data.product_discount.discount_type_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(res.data.product_set_price.original_price, res.data.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); if ($scope._dataArray.product_referral_display.category != 'undefined' && $scope._dataArray.product_referral_display.category != null) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } // $scope.dataTag = res.data.product_tags.split(","); $scope.qtyCurrentSize(res.data.product_total_stock); // $scope.buildVariantOption(res.data); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.mkCarousel = function(elem) { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { slidesToShow: 1, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var dataSend = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.dataRelation = res.data; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getIdUrl = function() { var getData = []; var returnData = ''; if (typeof $routeParams.product_id !== 'undefined') { getData = $routeParams.product_id; returnData = getData.split("-"); return returnData[0]; } }; $scope._stateReward = function(datain) { var state = false; /* console.log("_stateReward : reward_lifetime : ", datain.reward_lifetime); */ if (datain.length != 0) { state = true; } return state; }; $scope._getReward = function(datain, product_price, qty) { if (datain.length == 0) { return 'Data Reward Error'; } console.log("_getReward : product_price : ", product_price, " qty : ", qty); var reward = "NULL"; if (datain.reward_type_id == "101") {} else if (datain.reward_type_id == "102") {} else if (datain.reward_type_id == "103") { var reward_every_price = parseInt(datain.reward_every_price); var sum_product_price = Math.round(product_price) * qty; var reward_amount = parseInt(datain.reward_amount); console.log("_getReward : reward_every_price : ", reward_every_price, " sum_product_price : ", sum_product_price, " reward_amount : ", reward_amount); if (reward_every_price <= sum_product_price) { var divided = Math.floor(sum_product_price / reward_every_price); var multiplied = divided * reward_amount; console.log("_getReward : divided : ", divided, " multiplied : ", multiplied); reward = multiplied; } else { reward = "ZERO"; } } else { return 'Data Reward Type Id Error'; } return reward; }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleStatres.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleStatres.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined && discount_percent == 0 && discount_price == 0) { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } else { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, product_price, compare_price, discount_type_id, discount_price, discount_percent) { var calculate = 0; if (discount_type_id != undefined) { if (discount_type_id == "101") { calculate = price - discount_price; } else if (discount_type_id == "102") { calculate = price - ((discount_percent / 100) * price); } else if (discount_type_id == "103") { calculate = product_price; } else { calculate = price; } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.qtyCurrentSize = function(product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : ", "product_total_stock : ", product_total_stock); if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; if (product_total_stock >= 20) { for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else { for (var i = 0; i < parseInt(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } $scope.qtyShow($scope.qty_current_size); }; $scope.htmlSelectTime = 0; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } } $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").val() == undefined) { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); check_int = 1; } else if ($(".d_qty").val() == "? number:1 ?") { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); } else { check_int = parseInt($(".d_qty").val()); $(".d_qty").val(check_int); } return check_int; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems option_id:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems dataVariantsPick:", $scope.dataVariantsPick); if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); console.log("dataVariants :", dataVariants); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; if (dataVariants[i].sku != "") { $scope.product_sku = dataVariants[i].sku; } else { $scope.product_sku = $scope._dataArray.product_sku; } if (dataVariants[i].sku != "") { $scope.product_code = dataVariants[i].barcode; } else { $scope.product_code = $scope._dataArray.product_code; } $scope.product_price = $scope.calculate(dataVariants[i].price, $scope._dataArray.product_price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_type_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); break; } else { $scope.qty_current_size_state = false; $scope.buy_state = false; $scope.product_price = $scope._dataArray.product_price; $scope.product_compare_price = $scope._dataArray.product_compare_price; $scope.product_sku = $scope._dataArray.product_sku; $scope.product_code = $scope._dataArray.product_code; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope.viewInfo = 1; $scope.view = function(input) { $scope.viewInfo = input; } $scope._getDataArray($scope._getIdUrl()); // setTimeout(function() { // alert($('input[name=radiogroup]:checked').val()); // }, 700); $scope.clickckvalue = function() { var result = 0; $scope.promotion_list = $('input[name=radiogroup]:checked').val(); console.log("promotion_list : ", $scope.promotion_list); if ($('input[name=radiogroup]:checked').val() != "" && $('input[name=radiogroup]:checked').val() != undefined) { result = $('input[name=radiogroup]:checked').val(); } else { result = 0; } return result; } }; return promise; });/*_ui_share_app.directive('componentFooter', function($rootScope, $routeParams) { var templateName = 'componentFooter'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id: '=', background: '@', primary: '@', secondary: '@', name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) {}; return promise; });*/ _ui_share_app.factory('$componentProductSlide', function componentFooter($routeParams, $timeout) { return });_ui_share_app.directive('componentProductSlideA', function($rootScope, $routeParams) { var templateName = 'componentProductSlideA'; var componentMain = 'componentProductSlide'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', referralid: '@referralid', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarouselProduct = function(elem) { console.debug('mkCarouselProduct: trigger'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1330, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 1 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 1 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._productArray = []; $scope._productArrayDone = { load: true, done: false }; $scope._getProductArray = function(id) { $scope._productArrayDone = { load: true, done: false }; $scope._productArray = []; var filter_json = { "referral_id_array": [id] } console.log('filter_json_Product', filter_json); var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_Product', dataSend); GAEAPI.get('product/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._productArray = res.data.dataList; } $scope._productArrayDone = { load: false, done: true }; console.log('productArray', $scope._productArray); }); }; $scope._getProductArray($scope.referralid); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } }; return promise; });_ui_share_app.directive('componentProductTagA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentProductTagA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productid: '@productid', referralid : '@referralid', tag: '@tag', limit: '@limit', tagname: '@tagname', component: '@component', stylebutton: '@stylebutton', margin: '@margin', }; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_end': '?textEnd', }; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $q, $window, $location, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.slideProductDeal = function(elem) { $('.component-product-tag-a').css('height', '0'); $('.component-product-tag-a').css('opacity', '0'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { arrows: true, slidesToShow: 3 } }, { breakpoint: 768, settings: { arrows: true, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: true, slidesToShow: 1 } }] }).closest('section').addClass('active'); $('.component-product-tag-a').css('height', 'auto'); $('.component-product-tag-a').css('opacity', '1'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.consoleLog = function(text, data) { console.log(text, ' : ', data); }; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope._getDataArray = function(productid,referralid,tag, limit) { $scope.consoleLog('_getDataArray tag', tag); $scope.consoleLog('_getDataArray limit', limit); $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "referral_id_array" :[referralid], "tags": tag } var dataSend = { 'cur_page': 1, 'per_page': parseInt(limit), 'txt_filter_json': JSON.stringify(filter_json) }; $scope.consoleLog('_getDataArray tag dataSend', dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { $scope.consoleLog('_getDataArray output', output); if (output.ok == 1) { $scope.$apply(function() { for (var i = 0; i < output.data.dataList.length; i++) { $scope.consoleLog('_getDataArray : for : output.data.dataList : ', output.data.dataList[i]); $scope.consoleLog('_getDataArray : for : productid : ', $scope._viewRouteParams().product_id); if (output.data.dataList[i].product_id != $scope._idUrl($scope._viewRouteParams().product_id)) { $scope._dataArray.push(output.data.dataList[i]); } } /* $scope._dataArray = output.data.dataList; */ $scope.consoleLog('_getDataArray _dataArray', $scope._dataArray); }); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.$watch('tag', function(newValue, oldValue) { if (newValue) { $scope._getDataArray($scope.productid,$scope.referralid,$scope.tag, $scope.limit); } else { return; } }); }; return promise; });_ui_share_app.factory('$componentProductsDiscount', function componentProductsDiscount($routeParams, $timeout) { return });_ui_share_app.directive('componentProductsDiscountTypeA', function($rootScope, $routeParams) { var templateName = 'componentProductsDiscountTypeA'; var componentMain = 'componentProductsDiscount'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productcard: '@productcard', stylebutton: '@stylebutton', limit: '@limit', margin: '@margin', col: '@col', pre: '@pre', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._productcard = (typeof $scope.productcard !== 'undefined' && typeof $scope.productcard !== '') ? $scope.productcard : 'c'; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'border_button_small'; $scope._pre = Boolean((typeof $scope.pre !== 'undefined' && typeof $scope.pre !== '') ? $scope.pre : 'false'); $scope._limit = parseInt((typeof $scope.limit !== 'undefined' && typeof $scope.limit !== '') ? $scope.limit : 6); $scope.$watch('col', function(newValue, oldValue) { if (newValue) { $scope._col = newValue.toString().split(","); } }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined' && $scope._col[n] != '') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.productArray = false; $scope.loadMoreIsLoad = false; $scope.productCur = 1; $scope.productState = { load: false, done: false, more: false }; $scope.getProductsListsArray = function(cur, per) { if (cur == 1) { $scope.productArray = false; $scope.productState = $scope.stateData(true, false, $scope.productState.more); } var filter_json = {} var dataSend = { 'txt_cur_page': cur, 'txt_per_page': per, 'txt_filter_json': JSON.stringify(filter_json) }; GAEAPI.get('product/discounts', dataSend).then(function(output) { console.log("dataSend : ", dataSend, " output : ", output); if (output.ok == 1) { $scope.$apply(function() { var data = $scope.productArray; var dataNew = output.data; $scope.checkMore(data, dataNew); }); } if (cur == 1) { $scope.productState = $scope.stateData(false, true, $scope.productState.more); } }); }; $scope.checkMore = function(data, dataNew) { var dataOrigi = data; var dataTwo = dataNew.dataList; var total = dataNew.total_row; if (!data.length) { dataOrigi = dataTwo; $scope.productArray = dataOrigi; $scope.showMoreArray(dataOrigi.length, total); } else { $scope.productArray = dataOrigi.concat(dataTwo); $scope.showMoreArray($scope.productArray.length, total); $scope.loadMoreIsLoad = false; } }; $scope.showMoreArray = function(dataOrigiTotal, total) { console.log("showMoreArray : dataOrigiTotal : ", dataOrigiTotal, " total : ", total); if (dataOrigiTotal < total) { $scope.productState.more = true; } else { $scope.productState.more = false; } } $scope.stateData = function(_load_in, _done_in, _more_in) { var State = { load: _load_in, done: _done_in, more: _more_in }; return State; } $scope.loadMore = function() { $scope.productCur++; $scope.loadMoreIsLoad = true; $timeout(function() { $scope.getProductsListsArray($scope.productCur, $scope._limit); }, 300); } $scope.getProductsListsArray($scope.productCur, $scope._limit); }; return promise; });_ui_share_app.factory('$componentPromotion', function componentPromotion($routeParams, $timeout) { return });_ui_share_app.directive('componentPromotionListsD', function($rootScope, $routeParams) { var templateName = 'componentPromotionListsD'; var componentMain = 'componentPromotion'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', datanumber: '@datanumber', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarousel = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 3 } }, { breakpoint: 768, settings: { slidesToShow: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'cur_page': 1, 'per_page': parseInt($scope.datanumber), 'txt_badge_id' : 18, 'txt_sortby': 'promotion_lastest_create', }; GAEAPI.get('promotion/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend-promotion .-recommend-promotion[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend-promotion .-recommend-promotion[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.viewDataSize = function() { return -($(".item-promotion").height() + 100); }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPromotionListsE', function($rootScope, $routeParams) { var templateName = 'componentPromotionListsE'; var componentMain = 'componentPromotion'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', datanumber: '@datanumber', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarousel = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 3, } }, { breakpoint: 991, settings: { slidesToShow: 3 } }, { breakpoint: 768, settings: { slidesToShow: 2 } }, { breakpoint: 480, settings: { slidesToShow: 2 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'cur_page': 1, 'per_page': parseInt($scope.datanumber), 'txt_badge_id': 18, 'txt_sortby': 'promotion_lastest_create', }; GAEAPI.get('promotion/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend-promotion .-recommend-promotion[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend-promotion .-recommend-promotion[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.viewDataSize = function() { return -($(".item-promotion").height() + 100); }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentPromotionListsF', function($rootScope, $routeParams) { var templateName = 'componentPromotionListsF'; var componentMain = 'componentPromotion'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', datanumber: '@datanumber', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._console = (window.location.hostname == "localhost") ? true : false; $scope._component = "componentPromotionListsF"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* -------------------- */ $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { if ($scope._console) { console.log($scope._component, ' : ', functionName, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataApi = { load_more: { load: false, cur_page: 1, per_page: 12, total_rows: 0 }, promotion: { dataSend: {}, api: "promotion/lists", ok: false, dataArray: [], dataArrayState: { load: false, done: false } }, }; $scope.loadMore = function() { if (!$scope.dataApi.load_more.load) { $scope.dataApi.load_more.cur_page++; $scope.dataApi.load_more.load = true; $scope.getData().getRouteParams(function(res_params, res_state) { var txt_filter_json = { "type_number": 7 }; $scope.dataApi.promotion.dataSend = { 'cur_page': $scope.dataApi.load_more.cur_page, 'per_page': $scope.dataApi.load_more.per_page, 'txt_badge_id': 18, 'txt_sortby': 'promotion_lastest_create', 'txt_filter_json': JSON.stringify(txt_filter_json) } $scope.getData().dataSend($scope.dataApi.promotion.api, $scope.dataApi.promotion.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_shop, res_state) { $scope.dataApi.promotion.ok = res_ok; if ($scope.dataApi.promotion.dataArray.length < get_res_api_shop.data.total_rows) { var oldData = $scope.dataApi.promotion.dataArray; $scope.dataApi.promotion.dataArray = oldData.concat(get_res_api_shop.data.dataList); $scope.dataApi.load_more.total_rows = get_res_api_shop.data.total_rows; } else { $scope.dataApi.load_more.cur_page--; } $scope.dataApi.load_more.load = false; }); }); }); } } $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.promotion.dataArrayState = res_state; var txt_filter_json = { "type_number": 7 }; $scope.dataApi.promotion.dataSend = { 'cur_page': $scope.dataApi.load_more.cur_page, 'per_page': $scope.dataApi.load_more.per_page, 'txt_badge_id': 18, 'txt_sortby': 'promotion_lastest_create', 'txt_filter_json': JSON.stringify(txt_filter_json) } $scope.getData().dataSend($scope.dataApi.promotion.api, $scope.dataApi.promotion.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api_shop, res_state) { $scope.dataApi.promotion.ok = res_ok; $scope.dataApi.promotion.dataArray = get_res_api_shop.data.dataList; $scope.dataApi.promotion.dataArrayState = res_state; $scope.dataApi.load_more.total_rows = get_res_api_shop.data.total_rows; }); }); }); /* -------------------- */ }; return promise; });_ui_share_app.directive('componentPromotionListsG', function($rootScope, $routeParams) { var templateName = 'componentPromotionListsG'; var componentMain = 'componentPromotion'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', type: '@type', limit: '@limit', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = "componentPromotionListsG"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope._type = ($scope.type != undefined && $scope.type != "") ? parseInt($scope.type) : 5; $scope._per_page = ($scope.limit != undefined && $scope.limit != "") ? parseInt($scope.limit) : 6; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { console.log($scope._component, ' : ', functionName, ' : ', data); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, urlPdf: function(promotionPdf) { var _self = this; _self.consoleLog("link promotionPdf", promotionPdf); if (promotionPdf.length > 0) { window.open(promotionPdf[0].file_url, '_blank'); } }, more: function() { var _self = this; if (!$scope.dataApi.promotion.moreDataArrayState.load) { _self.getRouteParams(function(res_params, res_state) { $scope.dataApi.promotion.moreDataArrayState = res_state; $scope.dataApi.promotion.cur_page++; var txt_filter_json = { 'type_number': $scope._type } var dataSend = { 'cur_page': $scope.dataApi.promotion.cur_page, 'per_page': $scope._per_page, 'txt_sortby': 'promotion_lastest_create', 'txt_badge_id': 18, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.dataApi.promotion.dataSend = dataSend; _self.dataSend($scope.dataApi.promotion.api, $scope.dataApi.promotion.dataSend, function(res_api, res_dataSend) { _self.getApi(res_api, res_dataSend, function(res_ok, res_api, res_state) { if ($scope.dataApi.promotion.dataArray.length < res_api.data.total_rows) { $scope.dataApi.promotion.ok = res_api; var oldData = $scope.dataApi.promotion.dataArray; $scope.dataApi.promotion.dataArray = oldData.concat(res_api.data.dataList); $scope.dataApi.promotion.total_rows = res_api.data.total_rows; $scope.dataApi.promotion.moreDataArrayState = res_state; } else { $scope.dataApi.promotion.cur_page--; } }); }); }); } }, main: function() { var _self = this; _self.getRouteParams(function(res_params, res_state) { $scope.dataApi.promotion.dataArrayState = res_state; var txt_filter_json = { 'type_number': $scope._type } var dataSend = { 'cur_page': $scope.dataApi.promotion.cur_page, 'per_page': $scope._per_page, 'txt_sortby': 'promotion_lastest_create', 'txt_badge_id': 18, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.dataApi.promotion.dataSend = dataSend; _self.dataSend($scope.dataApi.promotion.api, $scope.dataApi.promotion.dataSend, function(res_api, res_dataSend) { _self.getApi(res_api, res_dataSend, function(res_ok, res_api, res_state) { $scope.dataApi.promotion.ok = res_api; $scope.dataApi.promotion.dataArray = res_api.data.dataList; $scope.dataApi.promotion.total_rows = res_api.data.total_rows; $scope.dataApi.promotion.dataArrayState = res_state; }); }); }); } } return getFunction; }; $scope.dataApi = { promotion: { dataSend: {}, api: "promotion/lists", ok: false, dataArray: [], dataArrayState: { load: false, done: false }, total_rows: 0, cur_page: 1, moreDataArrayState: { load: false, done: false } } }; $scope.getData().main(); }; return promise; }); _ui_share_app.directive('componentPromotionA', function ($rootScope, $routeParams) { var templateName = 'componentPromotionA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { background: '@background', type:'@type' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_1':'?textFirst', 'text_2':'?textSecond', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ var jsonFilter = JSON.stringify({'type_number':$scope.type}); var d = { 'cur_page':1, 'per_page':20, 'txt_sortby':'promotion_lastest_create', 'txt_json_filter':jsonFilter }; GAEAPI.get('promotion/lists',d,$scope).then(function(e){ if(e.ok === 1){ $scope.dataArray = e.data.dataList; } }); }; $scope.getData(); /* Badge */ $scope._showWeb = function (item) { var r = false; if (item.length <= 0) { return false; } else { for (var i = 0; i < item.length; i++) { if (item[i].badge_id == 18) { r = true; break; } } } return r; }; $scope._showApp = function (item) { var r = false; if (item.length <= 0) { return false; } else { for (var i = 0; i < item.length; i++) { if (item[i].badge_id == 19) { r = true; break; } } } return r; }; }; return promise; }); _ui_share_app.directive('componentPromotionB', function ($rootScope, $routeParams) { var templateName = 'componentPromotionB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { background: '@background', name:'@name', type:'@type' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_1':'?textFirst', 'text_2':'?textSecond', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ var jsonFilter = JSON.stringify({'type_number':$scope.type}); var d = { 'cur_page':1, 'per_page':20, 'txt_sortby':'promotion_lastest_create', 'txt_json_filter':jsonFilter }; GAEAPI.get('promotion/lists',d,$scope).then(function(e){ if(e.ok === 1){ $scope.dataArray = e.data.dataList; } }); }; $scope.getData(); /* Badge */ $scope._showWeb = function (item) { var r = false; if (item.length <= 0) { return false; } else { for (var i = 0; i < item.length; i++) { if (item[i].badge_id == 18) { r = true; break; } } } return r; }; $scope._showApp = function (item) { var r = false; if (item.length <= 0) { return false; } else { for (var i = 0; i < item.length; i++) { if (item[i].badge_id == 19) { r = true; break; } } } return r; }; }; return promise; }); _ui_share_app.directive('componentPromotionC', function ($rootScope, $routeParams) { var templateName = 'componentPromotionC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { item:'=item', imgpath:'@imgpath', promoname:'@promoname' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.data_discount = []; $scope.data_done = false; $scope.dataArray = []; $scope.getData = function(n_data){ $scope.data = []; $scope.data_discount = []; $scope.data_discount.discount_price = 0; $scope.data_done = false; var jsonFilter = { 'referral_id_array':[n_data] }; var d = { 'cur_page':1, 'per_page':8, 'txt_filter_json':JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists',d,$scope).then(function(e){ if(e.ok === 1){ if(e.data.dataList.length > 0){ $scope.data = e.data.dataList; for (var i = 0; i < e.data.dataList.length; i++) { console.log("test_discount : ",i,e.data.dataList[i].product_discount.length , e.data.dataList[i].product_discount); if(e.data.dataList[i].product_discount.length == undefined && e.data.dataList[i].product_discount){ console.log("test_discount",e.data.dataList[i].product_discount); $scope.data_discount.push(e.data.dataList[i]); if(e.data.dataList[i].product_discount.discount_price != 0){ $scope.data_discount[i].discount_price = (e.data.dataList[i].product_price-e.data.dataList[i].product_discount.discount_price); }else if(e.data.dataList[i].product_discount.discount_price == 0 && e.data.dataList[i].product_discount.discount_percent != 0){ $scope.data_discount[i].discount_price = (e.data.dataList[i].product_price-((e.data.dataList[i].product_price*e.data.dataList[i].product_discount.discount_percent)/100)); } console.log("test_discount_price",$scope.data_discount[i].discount_price); } } } } }); }; $scope.getData($scope.item.referral_id); /* Badge */ $scope._showWeb = function (item) { var r = false; if (item.length <= 0) { return false; } else { for (var i = 0; i < item.length; i++) { if (item[i].badge_id == 18) { r = true; break; } } } return r; }; $scope._showApp = function (item) { var r = false; if (item.length <= 0) { return false; } else { for (var i = 0; i < item.length; i++) { if (item[i].badge_id == 19) { r = true; break; } } } return r; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('componentPromotionD', function($rootScope, $routeParams) { var templateName = 'componentPromotionD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datain: '@datashow', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope.dataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var d = { 'cur_page': 1, 'per_page': 8, 'txt_badge_id': 18, }; GAEAPI.get('promotion/lists', d, $scope).then(function(e) { if (e.ok === 1) { $scope._dataArray = e.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.dataArray(); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentPromotionDb', function($rootScope, $routeParams) { var templateName = 'componentPromotionDb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datain: '@datashow', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope.dataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var d = { 'cur_page': 1, 'per_page': 8, 'txt_badge_id': 18, }; GAEAPI.get('promotion/lists', d, $scope).then(function(e) { if (e.ok === 1) { $scope._dataArray = e.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.dataArray(); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.factory('$componentPromotionDetail', function componentPromotionDetail($routeParams, $timeout) { return });_ui_share_app.directive('componentPromotionDetailTypeA', function($rootScope, $routeParams) { var templateName = 'componentPromotionDetailTypeA'; var componentMain = 'componentPromotionDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', navigation: '@navigation', navigationhref: '@navigationhref', navigationname: '@navigationname', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigation = (typeof $scope.navigation !== 'undefined' && typeof $scope.navigation !== '') ? Boolean($scope.navigation) : false; $scope.getRouteParams = function(callback) { var routeParams = $routeParams || false; callback(routeParams); }; $scope.dataPromotionId = []; $scope.promotion_create_time = ""; $scope.dataPromotionIdState = { load: false, done: false }; $scope.promotionId = function(params, callback) { var promotion_id = (params.promotion_id != undefined) ? params.promotion_id.split("-", 1).join("") : false; callback(promotion_id); }; $scope.getPromotionId = function(txt_promotion_id,callback) { $scope.dataPromotionIdState = $scope.StateData(true, false); var dataSend = { 'txt_promotion_id': txt_promotion_id }; GAEAPI.get('promotion/id', dataSend, $scope).then(function(output) { $scope.dataPromotionIdState = $scope.StateData(false, true); callback(output); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getRouteParams(function(params){ $scope.promotionId(params,function(promotion_id){ console.log('promotion_id : ',promotion_id); $scope.getPromotionId(promotion_id,function(output){ if (output.ok === 1) { $scope.dataPromotionId = output.data; $scope.promotion_create_time = moment(parseInt(output.data.promotion_create_time) * 1000).format('LL'); } }); }); }); }; return promise; });_ui_share_app.directive('componentPromotionDetailTypeB', function($rootScope, $routeParams) { var templateName = 'componentPromotionDetailTypeB'; var componentMain = 'componentPromotionDetail'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', navigation: '@navigation', navigationhref: '@navigationhref', navigationname: '@navigationname', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.navigation = (typeof $scope.navigation !== 'undefined' && typeof $scope.navigation !== '') ? Boolean($scope.navigation) : false; $scope.getRouteParams = function() { return $routeParams || false; }; $scope.dataPromotionId = []; $scope.promotion_create_time = ""; $scope.dataPromotionIdState = { load: false, done: false }; $scope.getPromotionId = function(txt_promotion_id) { $scope.dataPromotionIdState = $scope.StateData(true, false); var dataSend = { 'txt_promotion_id': txt_promotion_id }; GAEAPI.get('promotion/id', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope.dataPromotionId = output.data; $scope.promotion_create_time = moment(parseInt(output.data.promotion_create_time) * 1000).format('LL'); } $scope.dataPromotionIdState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getPromotionId($scope.getRouteParams().promotion_id); }; return promise; });_ui_share_app.directive('componentPromotionDetailA', function($rootScope, $routeParams) { var templateName = 'componentPromotionDetailA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id: '@id', name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewRouteParams = function() { return $routeParams || false; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); $scope.data_done = false; var d = { 'txt_promotion_id': id }; GAEAPI.get('promotion/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope._dataArray = e.data; } $scope._dataArrayState = $scope.StateData(true, false); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getPostIdFromURL = function() { var a = $scope.id; if (typeof $routeParams.promotion_id !== 'undefined') { test = parseInt($routeParams.promotion_id); a = $routeParams.promotion_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; $scope._getArray($scope._getPostIdFromURL()); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('componentPromotionDetailB', function($rootScope, $routeParams) { var templateName = 'componentPromotionDetailB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewRouteParams = function() { return $routeParams || false; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getArray = function() { $scope._dataArrayState = $scope.StateData(true, false); $scope.data_done = false; var d = { 'txt_promotion_id': $scope._getPostIdFromURL() }; GAEAPI.get('promotion/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope._dataArray = e.data; } $scope._dataArrayState = $scope.StateData(true, false); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getPostIdFromURL = function() { var a = $scope.id; if (typeof $routeParams.promotion_id !== 'undefined') { test = parseInt($routeParams.promotion_id); a = $routeParams.promotion_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; $scope._getArray($scope._getPostIdFromURL()); $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; }); _ui_share_app.directive('componentQuickAttribute', function ($rootScope) { var templateName = 'componentQuickAttribute'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productid:'@productid', card:'@card', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window, $http) { var api_host = GURL.base_api_url(); $scope.data = false; $scope.productOptionLevelArray = []; $scope.product_original_id = $scope.productid; $scope.getData = function(id){ var d = {'txt_product_id':id}; $http.get(api_host+'product/id',{params:d}).then(function(result){ var e = result.data; if(e.ok == 1){ $scope.data = e.data; $scope._data_product_id = e.data; if (typeof $scope._data_product_id.product_attribute.option_data !== 'undefined' && $scope._data_product_id.product_total_variant > 0) { if (typeof $scope._data_product_id.product_attribute.option_data.pclass_array !== 'undefined' && $scope._data_product_id.product_attribute.option_data.pclass_array.length) { /*$scope.buildMultipleQuantity(e.data);*/ for (var op = 0; op < $scope._data_product_id.product_attribute.option_data.pclass_array.length; op++) { $scope.productOptionLevelArray.push({ level_index: op, level_id: $scope._data_product_id.product_attribute.option_data.pclass_array[op].pclass_id, level_label: $scope._data_product_id.product_attribute.option_data.pclass_array[op].pclass_name, level_data: 0 }); } if (!$scope._data_product_id.product_attribute.option_data.variant_array.length) { $scope.optionToCalculateNext = true; } } else { $scope.optionToCalculateNext = true; } } else { $scope.optionToCalculateNext = true; } } if($scope.productOptionLevelArray.length){ $timeout(function(){ $('[quick-buy="'+$scope._data_product_id.product_id+'"]').hide(); },100); } else { /*$('[quick-buy="'+id+'"]').data("hide-test","true").hide();*/ } }); }; $scope.getData($scope.productid); /* Varaint */ $scope.selectedOptionTextJson = ''; $scope.productOptionLevelArray = []; $scope.optionToCalculateNext = false; $scope._chageProductByOptionId = function ($event, masterIndex, optionId) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } $scope.productOptionLevelArray[masterIndex].level_data = optionId; console.log('$scope.productOptionLevelArray: clicked!', $scope.productOptionLevelArray); var optionSelectedArray = []; for (var i = 0; i < $scope.productOptionLevelArray.length; i++) { if ($scope.productOptionLevelArray[i].level_data != 0) { optionSelectedArray.push($scope.productOptionLevelArray[i].level_data); } } if (optionSelectedArray.length === $scope._data_product_id.product_attribute.option_data.pclass_array.length) { $scope.optionToCalculateNext = true; } if (!$scope.optionToCalculateNext) { return; } for (var i = 0; i < $scope._data_product_id.product_attribute.option_data.variant_array.length; i++) { var _self = $scope._data_product_id.product_attribute.option_data.variant_array[i]; var _self_option = angular.fromJson(_self.option_id_json); if (compareArray(optionSelectedArray, _self_option)) { $scope._data_product_id.product_id = _self.product_id; $scope._data_product_id.product_price = _self.price; $scope._data_product_id.product_sku = _self.sku; /*$scope._data_product_id.product_compare_price = _self.compare_price;*/ $scope._data_product_id.product_variant_compare_price = _self.compare_price; console.log("selectedOptionTextJson: option", _self); $scope.selectedOptionTextJson = _self.option_id_json; console.log('selectedOptionTextJson: Key', '-' + optionSelectedArray.join('-') + '-'); /* Switch Quantity Input */ /* $scope.switchQuantityByKey('-' + optionSelectedArray.join('-') + '-');*/ /* Find Image Variant */ if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope._data_product_id.product_image.length; im++) { if ($scope._data_product_id.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } /*$timeout(function () { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { $scope._slickGoto('sliderDetailView', rightImagePosition); } else { angular.element('.d_gallery .item[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300);*/ } break; } } $scope.checkIfFullySelect($scope.product_original_id); }; $scope.buttonChangeState = function(t, varaint_id){ var b = $('.quick-buy-btn[varaint-product-id="'+varaint_id+'"]'); console.log("buttonChangeState",t); switch(t){ case 'wait': b.removeAttr("data-background-color"); b.html("Waiting.."); break; case 'finish': b.html("In Cart"); b.attr("data-background-color","primary_darkest"); break; default: b.removeAttr("data-background-color"); b.html('  Buy Now'); break; } }; $scope.buyProcess = function(product_id, quantity){ var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { $scope.buttonChangeState("wait", product_id); console.log("adding", product_id, quantity); UiCart.delegate.product.add(product_id, quantity); /* Pixel */ $pixelScript.event('AddToCart'); $timeout(function(){ $scope.buttonChangeState("finish", product_id); }, 1000); return; } else { return UiCart.delegate.modal.open(); } } return UiCart.delegate.modal.open(); }; $scope.showBuyOption = function(id){ console.log("checkIfFullySelect: full",id); if(!$('[quick-buy]').length){ return; } var original_id = id; var varaint_id = $scope._data_product_id.product_id; $(function(){ $('[quick-buy="'+original_id+'"]').html('
  Buy Now
'); $('.quick-buy-btn[product-id="'+original_id+'"]').on('click', function(){ var currentVaraintProductId = $(this).attr("varaint-product-id"); $scope.buyProcess($(this).attr("varaint-product-id"),1); }); $timeout(function(){ $('[quick-buy="'+original_id+'"]').show('fast'); }, 100); }); }; $scope.isFull = false; $scope.checkIfFullySelect = function(id){ var a = 0; for(var i = 0; i < $scope.productOptionLevelArray.length; i++){ if($scope.productOptionLevelArray[i].level_data != 0){ a = a + 1; } } if(a >= $scope.productOptionLevelArray.length){ console.log("checkIfFullySelect", a, $scope.productOptionLevelArray.length); $scope.isFull = true; $scope.showBuyOption(id); } }; }; return promise; }); _ui_share_app.directive('componentQuickAttributeB', function ($rootScope) { var templateName = 'componentQuickAttributeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productid:'@productid', card:'@card', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window, $http) { var api_host = GURL.base_api_url(); $scope.data = false; $scope.productOptionLevelArray = []; $scope.product_original_id = $scope.productid; $scope.getData = function(id){ var d = {'txt_product_id':id}; $http.get(api_host+'product/id',{params:d}).then(function(result){ var e = result.data; if(e.ok == 1){ $scope.data = e.data; $scope._data_product_id = e.data; if (typeof $scope._data_product_id.product_attribute.option_data !== 'undefined' && $scope._data_product_id.product_total_variant > 0) { if (typeof $scope._data_product_id.product_attribute.option_data.pclass_array !== 'undefined' && $scope._data_product_id.product_attribute.option_data.pclass_array.length) { /*$scope.buildMultipleQuantity(e.data);*/ for (var op = 0; op < $scope._data_product_id.product_attribute.option_data.pclass_array.length; op++) { $scope.productOptionLevelArray.push({ level_index: op, level_id: $scope._data_product_id.product_attribute.option_data.pclass_array[op].pclass_id, level_label: $scope._data_product_id.product_attribute.option_data.pclass_array[op].pclass_name, level_data: 0 }); } if (!$scope._data_product_id.product_attribute.option_data.variant_array.length) { $scope.optionToCalculateNext = true; } } else { $scope.optionToCalculateNext = true; } } else { $scope.optionToCalculateNext = true; } } if($scope.productOptionLevelArray.length){ $timeout(function(){ $('[quick-buy="'+$scope._data_product_id.product_id+'"]').hide(); },100); } else { /*$('[quick-buy="'+id+'"]').data("hide-test","true").hide();*/ } }); }; $scope.getData($scope.productid); /* Varaint */ $scope.selectedOptionTextJson = ''; $scope.productOptionLevelArray = []; $scope.optionToCalculateNext = false; $scope._chageProductByOptionId = function ($event, masterIndex, optionId) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } $scope.productOptionLevelArray[masterIndex].level_data = optionId; console.log('$scope.productOptionLevelArray: clicked!', $scope.productOptionLevelArray); var optionSelectedArray = []; for (var i = 0; i < $scope.productOptionLevelArray.length; i++) { if ($scope.productOptionLevelArray[i].level_data != 0) { optionSelectedArray.push($scope.productOptionLevelArray[i].level_data); } } if (optionSelectedArray.length === $scope._data_product_id.product_attribute.option_data.pclass_array.length) { $scope.optionToCalculateNext = true; } if (!$scope.optionToCalculateNext) { return; } for (var i = 0; i < $scope._data_product_id.product_attribute.option_data.variant_array.length; i++) { var _self = $scope._data_product_id.product_attribute.option_data.variant_array[i]; var _self_option = angular.fromJson(_self.option_id_json); if (compareArray(optionSelectedArray, _self_option)) { $scope._data_product_id.product_id = _self.product_id; $scope._data_product_id.product_price = _self.price; $scope._data_product_id.product_sku = _self.sku; /*$scope._data_product_id.product_compare_price = _self.compare_price;*/ $scope._data_product_id.product_variant_compare_price = _self.compare_price; console.log("selectedOptionTextJson: option", _self); $scope.selectedOptionTextJson = _self.option_id_json; console.log('selectedOptionTextJson: Key', '-' + optionSelectedArray.join('-') + '-'); /* Switch Quantity Input */ /* $scope.switchQuantityByKey('-' + optionSelectedArray.join('-') + '-');*/ /* Find Image Variant */ if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope._data_product_id.product_image.length; im++) { if ($scope._data_product_id.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } /*$timeout(function () { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { $scope._slickGoto('sliderDetailView', rightImagePosition); } else { angular.element('.d_gallery .item[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300);*/ } break; } } $scope.checkIfFullySelect($scope.product_original_id); }; $scope.buttonChangeState = function(t, varaint_id){ var b = $('.quick-buy-btn[varaint-product-id="'+varaint_id+'"]'); console.log("buttonChangeState",t); switch(t){ case 'wait': b.removeAttr("data-background-color"); b.html("Waiting.."); break; case 'finish': b.html("In Cart"); b.attr("data-background-color","primary_darkest"); break; default: b.removeAttr("data-background-color"); b.html('  Buy Now'); break; } }; $scope.buyProcess = function(product_id, quantity){ var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { $scope.buttonChangeState("wait", product_id); console.log("adding", product_id, quantity); UiCart.delegate.product.add(product_id, quantity); /* Pixel */ $pixelScript.event('AddToCart'); $timeout(function(){ $scope.buttonChangeState("finish", product_id); }, 1000); return; } else { return UiCart.delegate.modal.open(); } } return UiCart.delegate.modal.open(); }; $scope.showBuyOption = function(id){ console.log("checkIfFullySelect: full",id); if(!$('[quick-buy]').length){ return; } var original_id = id; var varaint_id = $scope._data_product_id.product_id; $(function(){ $('[quick-buy="'+original_id+'"]').html('
  สั่งซื้อเลย
'); $('.quick-buy-btn[product-id="'+original_id+'"]').on('click', function(){ var currentVaraintProductId = $(this).attr("varaint-product-id"); $scope.buyProcess($(this).attr("varaint-product-id"),1); }); $timeout(function(){ $('[quick-buy="'+original_id+'"]').show('fast'); }, 100); }); }; $scope.isFull = false; $scope.checkIfFullySelect = function(id){ var a = 0; for(var i = 0; i < $scope.productOptionLevelArray.length; i++){ if($scope.productOptionLevelArray[i].level_data != 0){ a = a + 1; } } if(a >= $scope.productOptionLevelArray.length){ console.log("checkIfFullySelect", a, $scope.productOptionLevelArray.length); $scope.isFull = true; $scope.showBuyOption(id); } }; }; return promise; }); _ui_share_app.directive('componentQuickAttributeC', function ($rootScope) { var templateName = 'componentQuickAttributeC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { productid:'@productid', card:'@card', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window, $http) { var api_host = GURL.base_api_url(); $scope.data = false; $scope.productOptionLevelArray = []; $scope.product_original_id = $scope.productid; $scope.getData = function(id){ var d = {'txt_product_id':id}; $http.get(api_host+'product/id',{params:d} , $scope).then(function(result){ var e = result.data; console.log("efjkdfjkdfjdfjdfjdfkd : ", result); if(e.ok == 1){ $scope.data = e.data; $scope._data_product_id = e.data; if (typeof $scope._data_product_id.product_attribute.option_data !== 'undefined' && $scope._data_product_id.product_total_variant > 0) { if (typeof $scope._data_product_id.product_attribute.option_data.pclass_array !== 'undefined' && $scope._data_product_id.product_attribute.option_data.pclass_array.length) { /*$scope.buildMultipleQuantity(e.data);*/ for (var op = 0; op < $scope._data_product_id.product_attribute.option_data.pclass_array.length; op++) { $scope.productOptionLevelArray.push({ level_index: op, level_id: $scope._data_product_id.product_attribute.option_data.pclass_array[op].pclass_id, level_label: $scope._data_product_id.product_attribute.option_data.pclass_array[op].pclass_name, level_data: 0 }); } if (!$scope._data_product_id.product_attribute.option_data.variant_array.length) { $scope.optionToCalculateNext = true; } } else { $scope.optionToCalculateNext = true; } } else { $scope.optionToCalculateNext = true; } } if($scope.productOptionLevelArray.length){ $timeout(function(){ $('[quick-buy="'+$scope._data_product_id.product_id+'"]').hide(); },100); } else { /*$('[quick-buy="'+id+'"]').data("hide-test","true").hide();*/ } }); }; $scope.getData($scope.productid); /* Varaint */ $scope.selectedOptionTextJson = ''; $scope.productOptionLevelArray = []; $scope.optionToCalculateNext = false; $scope._chageProductByOptionId = function ($event, masterIndex, optionId) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } $scope.productOptionLevelArray[masterIndex].level_data = optionId; console.log('$scope.productOptionLevelArray: clicked!', $scope.productOptionLevelArray); var optionSelectedArray = []; for (var i = 0; i < $scope.productOptionLevelArray.length; i++) { if ($scope.productOptionLevelArray[i].level_data != 0) { optionSelectedArray.push($scope.productOptionLevelArray[i].level_data); } } if (optionSelectedArray.length === $scope._data_product_id.product_attribute.option_data.pclass_array.length) { $scope.optionToCalculateNext = true; } if (!$scope.optionToCalculateNext) { return; } for (var i = 0; i < $scope._data_product_id.product_attribute.option_data.variant_array.length; i++) { var _self = $scope._data_product_id.product_attribute.option_data.variant_array[i]; var _self_option = angular.fromJson(_self.option_id_json); if (compareArray(optionSelectedArray, _self_option)) { $scope._data_product_id.product_id = _self.product_id; $scope._data_product_id.product_price = _self.price; $scope._data_product_id.product_sku = _self.sku; /*$scope._data_product_id.product_compare_price = _self.compare_price;*/ $scope._data_product_id.product_variant_compare_price = _self.compare_price; console.log("selectedOptionTextJson: option", _self); $scope.selectedOptionTextJson = _self.option_id_json; console.log('selectedOptionTextJson: Key', '-' + optionSelectedArray.join('-') + '-'); /* Switch Quantity Input */ /* $scope.switchQuantityByKey('-' + optionSelectedArray.join('-') + '-');*/ /* Find Image Variant */ if (_self.variant_image.length) { var rightImagePosition = 0; for (var im = 0; im < $scope._data_product_id.product_image.length; im++) { if ($scope._data_product_id.product_image[im].image_id == _self.variant_image[0].image_id) { rightImagePosition = im; break; } } /*$timeout(function () { console.log("Found Varaint Image", _self.variant_image[0].image_id); if ($(window).width <= 991) { $scope._slickGoto('sliderDetailView', rightImagePosition); } else { angular.element('.d_gallery .item[data-image-id="' + _self.variant_image[0].image_id + '"]').click(); } }, 300);*/ } break; } } $scope.checkIfFullySelect($scope.product_original_id); }; $scope.buttonChangeState = function(t, varaint_id){ var b = $('.quick-buy-btn[varaint-product-id="'+varaint_id+'"]'); console.log("buttonChangeState",t); switch(t){ case 'wait': b.removeAttr("data-background-color"); b.html("Waiting.."); break; case 'finish': b.html("In Cart"); b.attr("data-background-color","primary_darkest"); break; default: b.removeAttr("data-background-color"); b.html('  Buy Now'); break; } }; $scope.buyProcess = function(product_id, quantity){ var requireLogin = ($scope.requirelogin == 1 || $scope.requirelogin == true || $scope.requirelogin == 'true') ? true : false; if (!UiCustomerBox.delegate.get.isLogin() && requireLogin) { return UiCustomerBox.delegate.modal.openLoginForm(); } if (!UiCart.delegate.product.isSelected(product_id)) { if (!UiCart.delegate.product.isProgress(product_id)) { $scope.buttonChangeState("wait", product_id); console.log("adding", product_id, quantity); UiCart.delegate.product.add(product_id, quantity); /* Pixel */ $pixelScript.event('AddToCart'); $timeout(function(){ $scope.buttonChangeState("finish", product_id); }, 1000); return; } else { return UiCart.delegate.modal.open(); } } return UiCart.delegate.modal.open(); }; $scope.showBuyOption = function(id){ console.log("checkIfFullySelect: full",id); if(!$('[quick-buy]').length){ return; } var original_id = id; var varaint_id = $scope._data_product_id.product_id; $(function(){ $('[quick-buy="'+original_id+'"]').html('
BOOK NOW
'); $('.quick-buy-btn[product-id="'+original_id+'"]').on('click', function(){ var currentVaraintProductId = $(this).attr("varaint-product-id"); window.location.href = GURL.base_url() + "checkout?pdata="+currentVaraintProductId+'-1'; // $scope.buyProcess($(this).attr("varaint-product-id"),1); }); $timeout(function(){ $('[quick-buy="'+original_id+'"]').show('fast'); }, 100); }); }; $scope.isFull = false; $scope.checkIfFullySelect = function(id){ var a = 0; for(var i = 0; i < $scope.productOptionLevelArray.length; i++){ if($scope.productOptionLevelArray[i].level_data != 0){ a = a + 1; } } if(a >= $scope.productOptionLevelArray.length){ console.log("checkIfFullySelect", a, $scope.productOptionLevelArray.length); $scope.isFull = true; $scope.showBuyOption(id); } }; }; return promise; }); _ui_share_app.directive('componentQuotationPageB', function($rootScope, $routeParams) { var templateName = 'componentQuotationPageB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', texthead: '@texthead', imgpath: '@imgpath', contact: '@contact', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = { name: "componentQuotationPageB", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope._btnstyle = ($scope.stylebutton != undefined && $scope.stylebutton != "") ? $scope.stylebutton : "filled_button_xsmall"; $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, main: function() { var _self = this; } } return getFunction; }; $scope.form = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, isEmail: function(email, callback) { var state = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var res_state = state.test(email); callback(res_state); }, isPhone: function(phone, callback) { var state = /^(([0-9]{3}))([0-9]{3})([0-9]{4})$/; var res_state = state.test(phone); callback(res_state); }, isText: function(text, callback) { var _self = this; var state = text.length; var res_state = (state >= 5) ? true : false; callback(res_state); }, checkInput: function(data, callback) { var _self = this; var res_input_state = true; angular.forEach(data.input_array, function(item, index) { if (item.type.name == "input_email") { _self.isEmail(item.type.data, function(res_state) { res_input_state = (res_state) ? (!res_input_state) ? false : true : false; _self.consoleLog("isEmail", "res_state", res_state); if (!res_state) { $("[name='" + item.type.name + "']").addClass('error'); } else { $("[name='" + item.type.name + "']").removeClass('error'); } }); } else if (item.type.name == "input_phone") { _self.isPhone(item.type.data, function(res_state) { res_input_state = (res_state) ? (!res_input_state) ? false : true : false; _self.consoleLog("isPhone", "res_state", res_state); if (!res_state) { $("[name='" + item.type.name + "']").addClass('error'); } else { $("[name='" + item.type.name + "']").removeClass('error'); } }); } else if (item.type.name == "button_send") {} else if (item.type.name == "input_picture") {} else { _self.isText(item.type.data, function(res_state) { res_input_state = (res_state) ? (!res_input_state) ? false : true : false; _self.consoleLog("isText", "res_state", res_state); if (!res_state) { $("[name='" + item.type.name + "']").addClass('error'); } else { $("[name='" + item.type.name + "']").removeClass('error'); } }); } }); callback(res_input_state); }, submit: function(index) { var _self = this; _self.consoleLog("submit", "index", index); $scope.form_array[index].state = 'loader'; _self.checkInput($scope.form_array[index], function(res_input_state) { _self.consoleLog("submit", "res_input_state", res_input_state); if (res_input_state) { var formData = new FormData($('#contact-form-' + $scope.form_array[index].type)[0]); formData.append('input_owner_name', $scope.data_api.shop_current.data_array.shop_name); if ($scope.data_api.shop_current.data_array.shop_extend_data.contact_email != '') { formData.append('input_owner_contact', 'klitsadee.ch@worldcamera.co.th'); /* $scope.data_api.shop_current.data_array.shop_extend_data.contact_email */ /* klitsadee.ch@worldcamera.co.th */ $.ajax({ url: _ui_share_host + '../sendgrid/send-email_quotation_world.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { $scope.form_array[index].state = 'success'; }, error: function(jqXHR, textStatus, errorThrown) { $scope.form_array[index].state = 'error'; } }); } else { $scope.form_array[index].state = 'wait input'; } } else { $scope.form_array[index].state = 'wait input'; } }) } } return getFunction; }; $scope.form_array = [{ type: "a", state: 'wait input', input_array: [{ form_title: "ชื่อของท่าน(หรือชื่อบริษัท)", form_error: "กรุณากรอก ชื่อของท่าน(หรือชื่อบริษัท) ของท่าน", type: { name: "input_name", type: [{ type: "input" }, { type: "text" }], data: "" } }, { form_title: "หมายเลขโทรศัพท์ ", form_error: "กรุณากรอก หมายเลขโทรศัพท์ ของท่าน", type: { name: "input_phone", type: [{ type: "input" }, { type: "text" }], data: "" } }, { form_title: "อีเมล", form_error: "กรุณากรอก อีเมล ของท่าน", type: { name: "input_email", type: [{ type: "input" }, { type: "text" }], data: "" } }, { form_title: "รายละเอียดใบเสนอราคา", form_error: "กรุณากรอกราย รายละเอียดใบเสนอราคา ของท่าน", type: { name: "textarea_message", type: [{ type: "textarea" }, { type: "text" }], data: "" } }, { form_title: "", form_error: "", type: { name: "input_picture", type: [{ type: "file" }, { type: "file" }], data: "" } }, { form_title: "ส่งคำขอใบเสนอราคา", form_error: "", type: { name: "button_send", type: [{ type: "button" }, { type: "text" }], data: "" } }] }]; $scope.data_api = { shop_current: { data_send: {}, api: "shop/current", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.shop_current.data_array_state = state; _self.formatDataSend($scope.data_api.shop_current, function(res_data) { _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); }; return promise; });_ui_share_app.factory('$componentReferral', function componentReferral($routeParams, $timeout) { return });_ui_share_app.directive('componentReferralTypeA', function($rootScope, $routeParams) { var templateName = 'componentReferralTypeA'; var componentMain = 'componentReferral'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referralid: '@referralid', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._dataArray = []; $scope._getDataArray = function(referralid) { var dataSend = { 'txt_referral_id': referralid, 'txt_sortby': $scope.sort, }; GAEAPI.get('referral/relation', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; } }); }; $scope._getDataArray($scope.referralid); $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });/* Cart displat at right side of page */ var $inregisterPopup = {}; /* params */ $inregisterPopup.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentRegister/"; $inregisterPopup.templateRoot = 'root.php'; $inregisterPopup.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inregisterPopup.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inregisterPopup.install = function(shopId, customBuild) { /* dont install in (checkout, register) */ this.templateRoot = 'root.php'; $.get($inregisterPopup.path + 'componentRegister.css', function(response) { $('head').append(''); }); $.get($inregisterPopup.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inregisterPopup.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inregisterPopup.api = GURL.base_api_url(); /* Install */ /* register model */ $inregisterPopup.register = { firstname: '', lastname: '', email: '', password: '', pressing: false, errore_mail: false, errore_password: false, }; $inregisterPopup.error = { firstnameExist: false, lastnameExist: false, emailExist: false, firstname: false, lastname: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* register model */ /* validateRegister */ $inregisterPopup.validateRegister = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inregisterPopup.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusFirstname: function() { $inregisterPopup.error.firstname = false; $inregisterPopup.error.firstnameExist = false; $('#register-firstname-v1').css('border', ''); $("#register-error-firstname-v1").css('opacity', 0); }, focusLastname: function() { $inregisterPopup.error.lastname = false; $inregisterPopup.error.lastnameExist = false; $('#register-lastname-v1').css('border', ''); $("#register-error-lastname-v1").css('opacity', 0); }, focusEmail: function() { $inregisterPopup.error.email = false; $inregisterPopup.error.emailExist = false; $('#register-email-v1').css('border', ''); $("#register-error-email-v1").css('opacity', 0); }, focusPassword: function() { $inregisterPopup.error_password = false; $inregisterPopup.error.wrong_password = false; $('#register-password-v1').css('border', ''); $("#register-error-password-v1").css('opacity', 0); }, firstname: function() { var v = $('#register-firstname-v1').val(); var t = this; var valid = $inregisterPopup.helper.isFirstname(v, true); console.log("firstname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopup.shake(); $inregisterPopup.validateRegister().firstnameInputNullError(); $inregisterPopup.error_firstname = false; $inregisterPopup.error_firstnameExist = false; return false; } else { if (v.length > 0 && !valid) { $inregisterPopup.shake(); $inregisterPopup.validateRegister().firstnameInputError(); $inregisterPopup.error_firstname = true; return false; } else if (v.length > 0 && valid) { $inregisterPopup.validateRegister().firstnameOk(); return true; } } }, lastname: function() { var v = $('#register-lastname-v1').val(); var t = this; var valid = $inregisterPopup.helper.isLastname(v, true); console.log("lastname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopup.shake(); $inregisterPopup.validateRegister().lastnameInputNullError(); $inregisterPopup.error_lastname = false; $inregisterPopup.error_lastnameExist = false; return false; } else { if (v.length > 0 && valid) { $inregisterPopup.validateRegister().lastnameOk(); return true; } else { $inregisterPopup.shake(); $inregisterPopup.validateRegister().lastnameInputError(); $inregisterPopup.error_lastname = true; return false; } } }, email: function() { var v = $('#register-email-v1').val(); var t = this; if (v.length <= 0) { $inregisterPopup.shake(); $inregisterPopup.validateRegister().emailInputNullError(); $inregisterPopup.error_email = false; $inregisterPopup.error_emailExist = false; return false; } else { var valid = $inregisterPopup.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inregisterPopup.shake(); $inregisterPopup.validateRegister().emailInputError(); $inregisterPopup.error_email = true; return false; } else if (v.length > 0 && valid) { $inregisterPopup.validateRegister().emailOk(); return true; } } }, firstnameOk: function() { $('#register-firstname-v1').css('border', '2px solid green'); $inregisterPopup.validateRegister().firstnameInputOk(); }, lastnameOk: function() { $('#register-lastname-v1').css('border', '2px solid green'); $inregisterPopup.validateRegister().lastnameInputOk(); }, emailOk: function() { $('#register-email-v1').css('border', '2px solid green'); $inregisterPopup.validateRegister().emailInputOk(); }, firstnameInputOk: function() { $("#register-error-firstname-v1").removeClass("error"); $("#register-error-firstname-v1").css('opacity', 0); }, lastnameInputOk: function() { $("#register-error-lastname-v1").removeClass("error"); $("#register-error-lastname-v1").css('opacity', 0); }, emailInputOk: function() { $("#register-error-email-v1").removeClass("error"); $("#register-error-email-v1").css('opacity', 0); }, firstnameError: function() { $("#register-firstname-v1").css('border', '2px solid red'); }, lastnameError: function() { $("#register-lastname-v1").css('border', '2px solid red'); }, emailError: function() { $("#register-email-v1").css('border', '2px solid red'); }, firstnameInputError: function() { $inregisterPopup.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputError: function() { $inregisterPopup.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, emailInputRepeatedly: function() { $inregisterPopup.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('อีเมลนี้มีการลงทะเบียนเป็นสมาชิกแล้ว Email already exists'); }, passwordInputRepeatedly: function() { $("#register-password-v1").css('border', '1px solid #dddddd'); }, emailInputError: function() { $inregisterPopup.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, firstnameInputNullError: function() { $inregisterPopup.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); // $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputNullError: function() { $inregisterPopup.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); // $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format)'); }, emailInputNullError: function() { $inregisterPopup.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); // $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#register-password-v1').val(); if (v.length <= 0) { $inregisterPopup.validateRegister().passwordInputNullError(); $inregisterPopup.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inregisterPopup.error_password = false; $inregisterPopup.validateRegister().passwordOk(); return true; } else if (v.length > 0 && v.length < 6) { $inregisterPopup.error_password = true; $inregisterPopup.shake(); $inregisterPopup.validateRegister().passwordInputError(); return false; } }, passwordOk: function() { $("#register-password-v1").css('border', '2px solid green'); $inregisterPopup.validateRegister().passwordInputOk(); }, passwordInputOk: function() { $("#register-error-password-v1").removeClass("error"); $("#register-error-password-v1").css('opacity', 0); }, passwordError: function() { $("#register-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inregisterPopup.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); $("#register-error-password-v1").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputNullError: function() { $inregisterPopup.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); // $("#register-error-password-v1").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetFirstname: function() { $("#register-firstname-v1").css('border', ''); $("#register-firstname-v1").val(''); $("#register-error-firstname-v1").css('opacity', 0); }, resetLastname: function() { $("#register-lastname-v1").css('border', ''); $("#register-lastname-v1").val(''); $("#register-error-lastname-v1").css('opacity', 0); }, resetEmail: function() { $("#register-email-v1").css('border', ''); $("#register-email-v1").val(''); $("#register-error-email-v1").css('opacity', 0); }, resetPassword: function() { $("#register-password-v1").css('border', ''); $("#register-password-v1").val(''); $("#register-error-password-v1").css('opacity', 0); }, reset: function() { $inregisterPopup.validateRegister().resetFirstname(); $inregisterPopup.validateRegister().resetLastname(); $inregisterPopup.validateRegister().resetEmail(); $inregisterPopup.validateRegister().resetPassword(); }, }; return promise; }; /* validateRegister */ /* load html */ $inregisterPopup.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inregisterPopup.whenOnLoad = function(shopId) {}; $inregisterPopup.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isFirstname: function(firstname) { if (firstname.length > 1) { return true; } else { return false; } }, isLastname: function(lastname) { if (lastname.length > 1) { return true; } else { return false; } }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.register_v1_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.register_v1_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, registerDone: function() { var load = $('.register_v1_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_v1_done .register_done.from_background").addClass("is_open"); }, 100); }, registerUnDone: function() { var load = $('.register_v1_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_v1_done .register_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitRegister */ $inregisterPopup.submitRegister = function() { $inregisterPopup.register.firstname = $('#register-firstname-v1').val(); $inregisterPopup.register.lastname = $('#register-lastname-v1').val(); $inregisterPopup.register.email = $('#register-email-v1').val(); $inregisterPopup.register.password = $('#register-password-v1').val(); var userFirstname = $inregisterPopup.register.firstname; var userLastname = $inregisterPopup.register.lastname; var userEmail = $inregisterPopup.register.email; var userPass = $inregisterPopup.register.password; var userFirstnameValid = $inregisterPopup.validateRegister().firstname(); var userLastnameValid = $inregisterPopup.validateRegister().lastname(); var userEmailValid = $inregisterPopup.validateRegister().email(); var userPassValid = $inregisterPopup.validateRegister().password(); console.log("submitRegister", "userFirstnameValid : ", userFirstnameValid, "userLastnameValid : ", userLastnameValid, "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); if (!userFirstnameValid || !userLastnameValid || !userEmailValid || !userPassValid) { console.log("submitRegister", "return"); $inregisterPopup.shake(); return; } $inregisterPopup.validateRegister().checkEmail(userEmail, function(resultCheck) { console.log("submitRegister", resultCheck); if (resultCheck.ok == 0) { console.log('submitRegister true'); $inregisterPopup.validateRegister().emailInputRepeatedly(); $inregisterPopup.validateRegister().passwordInputRepeatedly(); } else { console.log('submitRegister false'); return $inregisterPopup.sendSubmitRegister(false); } }); }; /* submitRegister */ /* sendSubmitRegister */ $inregisterPopup.sendSubmitRegister = function(reCheck) { $inregisterPopup.register.pressing = true var userFirstname = $inregisterPopup.register.firstname; var userLastname = $inregisterPopup.register.lastname;; var userEmail = $inregisterPopup.register.email; var userPass = $inregisterPopup.register.password; console.log("sendSubmitRegister", reCheck); if (reCheck) { /* if error : firstname */ if (userFirstname.length <= 0) { $inregisterPopup.validateRegister().firstnameInputError(); } else { $inregisterPopup.validateRegister().firstnameOk(); } /* if error : lastname */ if (userLastname.length <= 0) { $inregisterPopup.validateRegister().lastnameInputError(); } else { $inregisterPopup.validateRegister().lastnameOk(); } /* if error : user */ if (userEmail.length <= 0) { $inregisterPopup.validateRegister().emailInputError(); } else { $inregisterPopup.validateRegister().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $inregisterPopup.validateRegister().passwordOk(); } else { $inregisterPopup.validateRegister().passwordInputError(); } /* firstname */ if (userFirstname.length > 0 && !$inregisterPopup.helper.isFirstname(userFirstname)) { $inregisterPopup.error_firstname = true; } else { $inregisterPopup.error_firstname = false; } /* lastname */ if (userLastname.length > 0 && !$inregisterPopup.helper.isLastname(userLastname)) { $inregisterPopup.error_lastname = true; } else { $inregisterPopup.error_lastname = false; } /* email */ if (userEmail.length > 0 && !$inregisterPopup.helper.isEmail(userEmail)) { $inregisterPopup.error_email = true; } else { $inregisterPopup.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inregisterPopup.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inregisterPopup.error_password = true; } console.log("sendSubmitRegister", "error_firstname : ", $inregisterPopup.error_firstname, "error_lastname : ", $inregisterPopup.error_lastname, "error_email : ", $inregisterPopup.error_email, "error_password : ", $inregisterPopup.error_password); if ($inregisterPopup.error_firstname || $inregisterPopup.error_lastname || $inregisterPopup.error_email || $inregisterPopup.error_password) { console.log("sendSubmitRegister return"); $inregisterPopup.shake(); return; } } /* loading */ $inregisterPopup.helper.pageLoad(); var dataSend = { 'txt_first_name': userFirstname, 'txt_last_name': userLastname, 'txt_email': userEmail, 'txt_password': userPass }; console.log("sendSubmitRegister txt_email :", dataSend); GAEAPI.post("ui/api/ui_customer_box/customer/register", dataSend).then(function(output) { console.log("sendSubmitRegister register", output); if (output.ok == 1) { $inregisterPopup.close(); $inregisterPopup.helper.pageUnLoad(); $inregisterPopup.helper.registerDone(); GAEAPI.get('customer/logout', {}).then(function(output_logout) { if (output_logout.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); } else { $inregisterPopup.helper.pageUnLoad(); alert("Register ผิดพลาด! กรุณาลองใหม่อีกครั้ง"); } }); /* loading */ }; /* sendSubmitRegister */ /* viewPassword */ $inregisterPopup.viewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); if (t === 'password') { e.attr('type', 'text'); } else { e.attr('type', 'password'); } }; $inregisterPopup.resetViewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); e.attr('type', 'password'); }; /* viewPassword */ $inregisterPopup.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inregisterPopup.isOpen = false; $inregisterPopup.open = function() { $inregisterPopup.resetViewPassword('register-password-v1'); $inregisterPopup.validateRegister().reset(); $(".register_overlay").addClass("is_open"); $('body').css({ 'overflow': 'hidden', 'height': '100%' }); timerAdjustOpen = setTimeout(function() { $(".register.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inregisterPopup.submitRegister(); } }); }; /* Open */ /* Close */ $inregisterPopup.close = function() { $(".register_overlay").removeClass("is_open"); $(".register.from_background").removeClass("is_open"); $('body').css({ 'overflow': 'auto' }); }; /* Close */ /* shake */ $inregisterPopup.shake = function() { $(".register.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".register.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inregisterPopup.login = function() { $inregisterPopup.close(); $inregisterPopup.helper.registerUnDone(); $inloginPopup.open(); } /* login */ /* toHome */ $inregisterPopup.toHome = function() { $inregisterPopup.helper.registerUnDone(); window.location.href = 'home'; }; /* toHome */ /* Init */ /* Init */ /* Init */ /* $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { case 541: $inregisterPopup.install(currentShopId, false); break; case 635: $inregisterPopup.install(currentShopId, false); break; case 646: $inregisterPopup.install(currentShopId, false); break; case 647: $inregisterPopup.install(currentShopId, false); break; case 676: $inregisterPopup.install(currentShopId, false); break; case 717: $inregisterPopup.install(currentShopId, false); break; case 718: $inregisterPopup.install(currentShopId, false); break; case 723: $inregisterPopup.install(currentShopId, false); break; case 729: $inregisterPopup.install(currentShopId, false); break; case 731: $inregisterPopup.install(currentShopId, false); break; case 741: $inregisterPopup.install(currentShopId, false); break; case 742: $inregisterPopup.install(currentShopId, false); break; case 732: $inregisterPopup.install(currentShopId, false); break; case 488: $inregisterPopup.install(currentShopId, false); break; default: break; } }); *//* Cart displat at right side of page */ var $inregisterPopupTypeProin = {}; /* params */ $inregisterPopupTypeProin.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentRegisterProin/"; $inregisterPopupTypeProin.templateRoot = 'root.php'; $inregisterPopupTypeProin.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inregisterPopupTypeProin.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inregisterPopupTypeProin.install = function(shopId, logo, customBuild) { /* dont install in (checkout, register) */ this.templateRoot = 'root.php'; var logoin = logo; $.get($inregisterPopupTypeProin.path + 'componentRegisterProin.css', function(response) { $('head').append(''); }); $.get($inregisterPopupTypeProin.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, logo: logoin, custom: customBuild, path: $inregisterPopupTypeProin.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inregisterPopupTypeProin.api = GURL.base_api_url(); /* Install */ /* register model */ $inregisterPopupTypeProin.register = { firstname: '', lastname: '', email: '', password: '', pressing: false, errore_mail: false, errore_password: false, }; $inregisterPopupTypeProin.error = { firstnameExist: false, lastnameExist: false, emailExist: false, firstname: false, lastname: false, email: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* register model */ /* validateRegister */ $inregisterPopupTypeProin.validateRegister = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inregisterPopupTypeProin.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, focusFirstname: function() { $inregisterPopupTypeProin.error.firstname = false; $inregisterPopupTypeProin.error.firstnameExist = false; $('#register-firstname-v1').css('border', ''); }, focusLastname: function() { $inregisterPopupTypeProin.error.lastname = false; $inregisterPopupTypeProin.error.lastnameExist = false; $('#register-lastname-v1').css('border', ''); }, focusEmail: function() { $inregisterPopupTypeProin.error.email = false; $inregisterPopupTypeProin.error.emailExist = false; $('#register-email-v1').css('border', ''); }, focusPassword: function() { $inregisterPopupTypeProin.error_password = false; $inregisterPopupTypeProin.error.wrong_password = false; $('#register-password-v1').css('border', ''); }, firstname: function() { var v = $('#register-firstname-v1').val(); var t = this; var valid = $inregisterPopupTypeProin.helper.isFirstname(v, true); console.log("firstname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeProin.shake(); $inregisterPopupTypeProin.validateRegister().firstnameInputNullError(); $inregisterPopupTypeProin.error_firstname = false; $inregisterPopupTypeProin.error_firstnameExist = false; return false; } else { if (v.length > 0 && !valid) { $inregisterPopupTypeProin.shake(); $inregisterPopupTypeProin.validateRegister().firstnameInputError(); $inregisterPopupTypeProin.error_firstname = true; return false; } else if (v.length > 0 && valid) { $inregisterPopupTypeProin.validateRegister().firstnameOk(); return true; } } }, lastname: function() { var v = $('#register-lastname-v1').val(); var t = this; var valid = $inregisterPopupTypeProin.helper.isLastname(v, true); console.log("lastname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeProin.shake(); $inregisterPopupTypeProin.validateRegister().lastnameInputNullError(); $inregisterPopupTypeProin.error_lastname = false; $inregisterPopupTypeProin.error_lastnameExist = false; return false; } else { if (v.length > 0 && valid) { $inregisterPopupTypeProin.validateRegister().lastnameOk(); return true; } else { $inregisterPopupTypeProin.shake(); $inregisterPopupTypeProin.validateRegister().lastnameInputError(); $inregisterPopupTypeProin.error_lastname = true; return false; } } }, email: function() { var v = $('#register-email-v1').val(); var t = this; if (v.length <= 0) { $inregisterPopupTypeProin.shake(); $inregisterPopupTypeProin.validateRegister().emailInputNullError(); $inregisterPopupTypeProin.error_email = false; $inregisterPopupTypeProin.error_emailExist = false; return false; } else { var valid = $inregisterPopupTypeProin.helper.isEmail(v, true); if (v.length > 0 && !valid) { $inregisterPopupTypeProin.shake(); $inregisterPopupTypeProin.validateRegister().emailInputError(); $inregisterPopupTypeProin.error_email = true; return false; } else if (v.length > 0 && valid) { $inregisterPopupTypeProin.validateRegister().emailOk(); return true; } } }, firstnameOk: function() { $('#register-firstname-v1').css('border', '2px solid green'); $inregisterPopupTypeProin.validateRegister().firstnameInputOk(); }, lastnameOk: function() { $('#register-lastname-v1').css('border', '2px solid green'); $inregisterPopupTypeProin.validateRegister().lastnameInputOk(); }, emailOk: function() { $('#register-email-v1').css('border', '2px solid green'); $inregisterPopupTypeProin.validateRegister().emailInputOk(); }, firstnameInputOk: function() { $("#register-error-firstname-v1").removeClass("error"); $("#register-error-firstname-v1").css('opacity', 0); }, lastnameInputOk: function() { $("#register-error-lastname-v1").removeClass("error"); $("#register-error-lastname-v1").css('opacity', 0); }, emailInputOk: function() { $("#register-error-email-v1").removeClass("error"); $("#register-error-email-v1").css('opacity', 0); }, firstnameError: function() { $("#register-firstname-v1").css('border', '2px solid red'); }, lastnameError: function() { $("#register-lastname-v1").css('border', '2px solid red'); }, emailError: function() { $("#register-email-v1").css('border', '2px solid red'); }, firstnameInputError: function() { $inregisterPopupTypeProin.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputError: function() { $inregisterPopupTypeProin.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, emailInputRepeatedly: function() { $inregisterPopupTypeProin.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('อีเมลนี้มีการลงทะเบียนเป็นสมาชิกแล้ว Email already exists'); }, passwordInputRepeatedly: function() { $("#register-password-v1").css('border', '1px solid #dddddd'); }, emailInputError: function() { $inregisterPopupTypeProin.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, firstnameInputNullError: function() { $inregisterPopupTypeProin.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); // $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputNullError: function() { $inregisterPopupTypeProin.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); // $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format)'); }, emailInputNullError: function() { $inregisterPopupTypeProin.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); // $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, password: function() { var v = $('#register-password-v1').val(); if (v.length <= 0) { $inregisterPopupTypeProin.validateRegister().passwordInputNullError(); $inregisterPopupTypeProin.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inregisterPopupTypeProin.error_password = false; $inregisterPopupTypeProin.validateRegister().passwordOk(); return true; } else if (v.length > 0 && v.length < 6) { $inregisterPopupTypeProin.error_password = true; $inregisterPopupTypeProin.shake(); $inregisterPopupTypeProin.validateRegister().passwordInputError(); return false; } }, passwordOk: function() { $("#register-password-v1").css('border', '2px solid green'); $inregisterPopupTypeProin.validateRegister().passwordInputOk(); }, passwordInputOk: function() { $("#register-error-password-v1").removeClass("error"); $("#register-error-password-v1").css('opacity', 0); }, passwordError: function() { $("#register-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inregisterPopupTypeProin.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); $("#register-error-password-v1").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputNullError: function() { $inregisterPopupTypeProin.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); // $("#register-error-password-v1").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetFirstname: function() { $("#register-firstname-v1").css('border', ''); $("#register-firstname-v1").val(''); $("#register-error-firstname-v1").css('opacity', 0); }, resetLastname: function() { $("#register-lastname-v1").css('border', ''); $("#register-lastname-v1").val(''); $("#register-error-lastname-v1").css('opacity', 0); }, resetEmail: function() { $("#register-email-v1").css('border', ''); $("#register-email-v1").val(''); $("#register-error-email-v1").css('opacity', 0); }, resetPassword: function() { $("#register-password-v1").css('border', ''); $("#register-password-v1").val(''); $("#register-error-password-v1").css('opacity', 0); }, reset: function() { $inregisterPopupTypeProin.validateRegister().resetFirstname(); $inregisterPopupTypeProin.validateRegister().resetLastname(); $inregisterPopupTypeProin.validateRegister().resetEmail(); $inregisterPopupTypeProin.validateRegister().resetPassword(); }, }; return promise; }; /* validateRegister */ /* load html */ $inregisterPopupTypeProin.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inregisterPopupTypeProin.whenOnLoad = function(shopId) {}; $inregisterPopupTypeProin.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isFirstname: function(firstname) { if (firstname.length > 1) { return true; } else { return false; } }, isLastname: function(lastname) { if (lastname.length > 1) { return true; } else { return false; } }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.register_vProin_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.register_vProin_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, registerDone: function() { var load = $('.register_vProin_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vProin_done .register_done.from_background").addClass("is_open"); }, 100); }, registerUnDone: function() { var load = $('.register_vProin_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vProin_done .register_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitRegister */ $inregisterPopupTypeProin.submitRegister = function() { $inregisterPopupTypeProin.register.firstname = $('#register-firstname-v1').val(); $inregisterPopupTypeProin.register.lastname = $('#register-lastname-v1').val(); $inregisterPopupTypeProin.register.email = $('#register-email-v1').val(); $inregisterPopupTypeProin.register.password = $('#register-password-v1').val(); var userFirstname = $inregisterPopupTypeProin.register.firstname; var userLastname = $inregisterPopupTypeProin.register.lastname; var userEmail = $inregisterPopupTypeProin.register.email; var userPass = $inregisterPopupTypeProin.register.password; var userFirstnameValid = $inregisterPopupTypeProin.validateRegister().firstname(); var userLastnameValid = $inregisterPopupTypeProin.validateRegister().lastname(); var userEmailValid = $inregisterPopupTypeProin.validateRegister().email(); var userPassValid = $inregisterPopupTypeProin.validateRegister().password(); console.log("submitRegister", "userFirstnameValid : ", userFirstnameValid, "userLastnameValid : ", userLastnameValid, "userEmailValid : ", userEmailValid, "userPassValid : ", userPassValid); if (!userFirstnameValid || !userLastnameValid || !userEmailValid || !userPassValid) { console.log("submitRegister", "return"); $inregisterPopupTypeProin.shake(); return; } $inregisterPopupTypeProin.validateRegister().checkEmail(userEmail, function(resultCheck) { console.log("submitRegister", resultCheck); if (resultCheck.ok == 0) { console.log('submitRegister true'); $inregisterPopupTypeProin.validateRegister().emailInputRepeatedly(); $inregisterPopupTypeProin.validateRegister().passwordInputRepeatedly(); } else { console.log('submitRegister false'); return $inregisterPopupTypeProin.sendSubmitRegister(false); } }); }; /* submitRegister */ /* sendSubmitRegister */ $inregisterPopupTypeProin.sendSubmitRegister = function(reCheck) { $inregisterPopupTypeProin.register.pressing = true var userFirstname = $inregisterPopupTypeProin.register.firstname; var userLastname = $inregisterPopupTypeProin.register.lastname;; var userEmail = $inregisterPopupTypeProin.register.email; var userPass = $inregisterPopupTypeProin.register.password; console.log("sendSubmitRegister", reCheck); if (reCheck) { /* if error : firstname */ if (userFirstname.length <= 0) { $inregisterPopupTypeProin.validateRegister().firstnameInputError(); } else { $inregisterPopupTypeProin.validateRegister().firstnameOk(); } /* if error : lastname */ if (userLastname.length <= 0) { $inregisterPopupTypeProin.validateRegister().lastnameInputError(); } else { $inregisterPopupTypeProin.validateRegister().lastnameOk(); } /* if error : user */ if (userEmail.length <= 0) { $inregisterPopupTypeProin.validateRegister().emailInputError(); } else { $inregisterPopupTypeProin.validateRegister().emailOk(); } /* if error : pass */ if (userPass.length <= 0) { $inregisterPopupTypeProin.validateRegister().passwordOk(); } else { $inregisterPopupTypeProin.validateRegister().passwordInputError(); } /* firstname */ if (userFirstname.length > 0 && !$inregisterPopupTypeProin.helper.isFirstname(userFirstname)) { $inregisterPopupTypeProin.error_firstname = true; } else { $inregisterPopupTypeProin.error_firstname = false; } /* lastname */ if (userLastname.length > 0 && !$inregisterPopupTypeProin.helper.isLastname(userLastname)) { $inregisterPopupTypeProin.error_lastname = true; } else { $inregisterPopupTypeProin.error_lastname = false; } /* email */ if (userEmail.length > 0 && !$inregisterPopupTypeProin.helper.isEmail(userEmail)) { $inregisterPopupTypeProin.error_email = true; } else { $inregisterPopupTypeProin.error_email = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inregisterPopupTypeProin.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inregisterPopupTypeProin.error_password = true; } console.log("sendSubmitRegister", "error_firstname : ", $inregisterPopupTypeProin.error_firstname, "error_lastname : ", $inregisterPopupTypeProin.error_lastname, "error_email : ", $inregisterPopupTypeProin.error_email, "error_password : ", $inregisterPopupTypeProin.error_password); if ($inregisterPopupTypeProin.error_firstname || $inregisterPopupTypeProin.error_lastname || $inregisterPopupTypeProin.error_email || $inregisterPopupTypeProin.error_password) { console.log("sendSubmitRegister return"); $inregisterPopupTypeProin.shake(); return; } } /* loading */ $inregisterPopupTypeProin.helper.pageLoad(); var dataSend = { 'txt_first_name': userFirstname, 'txt_last_name': userLastname, 'txt_email': userEmail, 'txt_password': userPass }; console.log("sendSubmitRegister txt_email :", dataSend); GAEAPI.post("ui/api/ui_customer_box/customer/register", dataSend).then(function(output) { console.log("sendSubmitRegister register", output); if (output.ok == 1) { $inregisterPopupTypeProin.close(); $inregisterPopupTypeProin.helper.pageUnLoad(); $inregisterPopupTypeProin.helper.registerDone(); GAEAPI.get('customer/logout', {}).then(function(output_logout) { if (output_logout.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); } else { $inregisterPopupTypeProin.helper.pageUnLoad(); alert("Register ผิดพลาด! กรุณาลองใหม่อีกครั้ง"); } }); /* loading */ }; /* sendSubmitRegister */ /* viewPassword */ $inregisterPopupTypeProin.viewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); if (t === 'password') { e.attr('type', 'text'); } else { e.attr('type', 'password'); } }; $inregisterPopupTypeProin.resetViewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); e.attr('type', 'password'); }; /* viewPassword */ $inregisterPopupTypeProin.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inregisterPopupTypeProin.isOpen = false; $inregisterPopupTypeProin.open = function() { $inregisterPopupTypeProin.resetViewPassword('register-password-v1'); $inregisterPopupTypeProin.validateRegister().reset(); $(".register_overlay").addClass("is_open"); $('body').css({ 'overflow': 'hidden', 'height': '100%' }); timerAdjustOpen = setTimeout(function() { $(".register.from_background").addClass("is_open"); }, 100); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inregisterPopupTypeProin.submitRegister(); } }); }; /* Open */ /* Close */ $inregisterPopupTypeProin.close = function() { $(".register_overlay").removeClass("is_open"); $(".register.from_background").removeClass("is_open"); $('body').css({ 'overflow': 'auto' }); }; /* Close */ /* shake */ $inregisterPopupTypeProin.shake = function() { $(".register.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".register.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inregisterPopupTypeProin.login = function() { $inregisterPopupTypeProin.close(); $inregisterPopupTypeProin.helper.registerUnDone(); $inloginPopup.open(); } /* login */ /* toHome */ $inregisterPopupTypeProin.toHome = function() { $inregisterPopupTypeProin.helper.registerUnDone(); window.location.href = 'home'; }; /* toHome */ /* Init */ /* Init */ /* Init */ /* $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { case 541: $inregisterPopupTypeProin.install(currentShopId, false); break; case 635: $inregisterPopupTypeProin.install(currentShopId, false); break; case 646: $inregisterPopupTypeProin.install(currentShopId, false); break; case 647: $inregisterPopupTypeProin.install(currentShopId, false); break; case 676: $inregisterPopupTypeProin.install(currentShopId, false); break; case 717: $inregisterPopupTypeProin.install(currentShopId, false); break; case 718: $inregisterPopupTypeProin.install(currentShopId, false); break; case 723: $inregisterPopupTypeProin.install(currentShopId, false); break; case 729: $inregisterPopupTypeProin.install(currentShopId, false); break; case 731: $inregisterPopupTypeProin.install(currentShopId, false); break; case 741: $inregisterPopupTypeProin.install(currentShopId, false); break; case 742: $inregisterPopupTypeProin.install(currentShopId, false); break; case 732: $inregisterPopupTypeProin.install(currentShopId, false); break; case 488: $inregisterPopupTypeProin.install(currentShopId, false); break; default: break; } }); */var $inregisterPopupTypeCct = { path: CUR_THEME.devsource_url() + "dev.sugarfree/share/componentRegisterTypeCct/", icnPath: CUR_THEME.extensions_url() + "../../assets/", templateRoot: "root.php", api: GURL.base_api_url(), }; $inregisterPopupTypeCct.install = function(shopId, customBuild) { $.get($inregisterPopupTypeCct.path + 'componentRegisterTypeCct.css', function(response) { $('head').append(''); }); $.get($inregisterPopupTypeCct.path + 'root.php', { imgpath: $inregisterPopupTypeCct.icnPath, shopId: shopId, custom: customBuild, path: $inregisterPopupTypeCct.path }, function(response) { $('body').append(response); }); }; $inregisterPopupTypeCct.display = function() { var display = { consoleLog: function(statu, data) { var statuConsole = true; if (statuConsole) { console.log(statu, data); } }, contronlClass: function(class_in, array_in) { $(class_in).css(array_in); }, addClass: function(class_in, status) { var class_add = $(class_in); if (!class_add.hasClass(status)) { class_add.addClass(status); } }, removeClass: function(class_in, status) { var class_remove = $(class_in); if (class_remove.hasClass(status)) { class_remove.removeClass(status); } }, formPass: function(class_in) { $(class_in).css('border', '2px solid green'); }, formError: function(class_in) { $(class_in).css('border', '2px solid red'); }, getVal: function(class_or_id) { var get_val = $(class_or_id).val(); return get_val; }, postVal: function(class_or_id, text) { var get_val = $(class_or_id).html(text); }, postAppend: function(class_in, code_in) { $(class_in).append(code_in); }, setCss: function(class_in, styleOne, styleTwo) { $(class_in).css(styleOne, styleTwo); }, setVal: function(class_in, val) { $(class_in).val(val); }, reset: function() { /* firstname */ $inverificationPopupTypeCct.display().setCss("#register-firstname-v1", "border", ""); $inverificationPopupTypeCct.display().setVal("#register-firstname-v1", ""); $inverificationPopupTypeCct.display().setCss("#register-error-firstname-v1", "opacity", 0); /* lastname */ $inverificationPopupTypeCct.display().setCss("#register-lastname-v1", "border", ""); $inverificationPopupTypeCct.display().setVal("#register-lastname-v1", ""); $inverificationPopupTypeCct.display().setCss("#register-error-lastname-v1", "opacity", 0); /* email */ $inverificationPopupTypeCct.display().setCss("#register-email-v1", "border", ""); $inverificationPopupTypeCct.display().setVal("#register-email-v1", ""); $inverificationPopupTypeCct.display().setCss("#register-error-email-v1", "opacity", 0); /* mobile */ $inverificationPopupTypeCct.display().setCss("#register-mobile-v1", "border", ""); $inverificationPopupTypeCct.display().setVal("#register-mobile-v1", ""); $inverificationPopupTypeCct.display().setCss("#register-error-mobile-v1", "opacity", 0); /* amwayid */ $inverificationPopupTypeCct.display().setCss("#register-amwayid-v1", "border", ""); $inverificationPopupTypeCct.display().setVal("#register-amwayid-v1", ""); $inverificationPopupTypeCct.display().setCss("#register-error-amwayid-v1", "opacity", 0); /* team */ $inverificationPopupTypeCct.display().setCss("#register-group-v1", "border", ""); $inverificationPopupTypeCct.display().setVal("#register-group-v1", 0); $inverificationPopupTypeCct.display().setCss("#register-error-group-v1", "opacity", 0); /* password */ $inverificationPopupTypeCct.display().setCss("#register-password-v1", "border", ""); $inverificationPopupTypeCct.display().setVal("#register-password-v1", ""); $inverificationPopupTypeCct.display().setCss("#register-error-password-v1", "opacity", 0); /* confirm-password */ $inverificationPopupTypeCct.display().setCss("#register-confirm-password-v1", "border", ""); $inverificationPopupTypeCct.display().setVal("#register-confirm-password-v1", ""); $inverificationPopupTypeCct.display().setCss("#register-error-confirm-password-v1", "opacity", 0); }, }; return display; }; $inregisterPopupTypeCct.api = function() { var api = { checkOk: function(data, callback) { var check_ok = false; if (data.ok == 1) { check_ok = true; } callback(check_ok); }, customerRegister: function(first, last, email, mobile, abo, group, password, callback) { var filter_json = { "mobile_phone": mobile, "abo_number": abo, "customer_group_id": group, } var dataSend = { 'txt_first_name': first, 'txt_last_name': last, 'txt_email': email, 'txt_password': password, 'txt_extend_data_json': JSON.stringify(filter_json), }; $inverificationPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : api : customerRegister : dataSend : ", dataSend); UiCustomerBox.api.post("customer/register", dataSend).then(function(output) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : customerRegister : output : ", output); $inverificationPopupTypeCct.api().checkOk(output, function(check_ok) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : checkOk : check_ok : ", check_ok); if (check_ok) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : check_ok : ", "OK"); } else { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : check_ok : ", "ERROR"); } callback(check_ok); }); }); }, currentData: function(callback) { var dataSend = {}; var get_current_data = {}; $inverificationPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : api : currentData : dataSend : ", dataSend); UiCustomerBox.api.get("current/data", dataSend).then(function(output) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : currentData : output : ", output); $inverificationPopupTypeCct.api().checkOk(output, function(check_ok) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : checkOk : check_ok : ", check_ok); if (check_ok) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : check_ok : ", "OK"); get_current_data = output; } else { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : check_ok : ", "ERROR"); } callback(get_current_data, check_ok); }); }); }, }; return api; }; $inregisterPopupTypeCct.check = function() { var check = { checkFormat: function(class_or_id, isFunction, callback) { var form_in = $inregisterPopupTypeCct.display().getVal(class_or_id); $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : form : ", form_in); var check_format = false; var check_alert = ""; if (isFunction == 'length') { $inregisterPopupTypeCct.check().isLength(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isLength : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isLength : status_check : ", "ERROR"); check_alert = "กรุณากรอก" } }); } else if (isFunction == 'select') { $inregisterPopupTypeCct.check().isSelect(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isSelect : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isSelect : status_check : ", "ERROR"); check_alert = "กรุณาเลือก" } }); } else if (isFunction == 'email') { $inregisterPopupTypeCct.check().isEmail(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isEmail : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isEmail : status_check : ", "ERROR"); check_alert = "ตรวจสอบรูปแบบ" } }); } else if (isFunction == 'mobile') { $inregisterPopupTypeCct.check().isMobile(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isMobile : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isMobile : status_check : ", "ERROR"); check_alert = "ตรวจสอบรูปแบบ" } }); } else if (isFunction == 'password') { $inregisterPopupTypeCct.check().isPassword(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isPassword : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isPassword : status_check : ", "ERROR"); check_alert = "ตรวจสอบรูปแบบ" } }); } callback(form_in, check_format, check_alert); }, checkPassword: function(class_or_id_password, class_or_id_password_confirm, callback) { var form_in_password = $inregisterPopupTypeCct.display().getVal(class_or_id_password); var form_in_password_confirm = $inregisterPopupTypeCct.display().getVal(class_or_id_password_confirm); $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkPassword : form_in_password : ", form_in_password); $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkPassword : form_in_password_confirm : ", form_in_password_confirm); var check_format_password = ""; var check_alert = ""; var check_format = false; if (form_in_password != "" && form_in_password_confirm != "" && form_in_password == form_in_password_confirm) { $inregisterPopupTypeCct.check().isPassword(form_in_password, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkPassword : isPassword : status_check : ", "OK"); check_format_password = form_in_password; check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkPassword : isPassword : status_check : ", "ERROR"); check_alert = "กรุณากรอก Password and Confirm Password ให้ตรงกัน"; } }); } else if (form_in_password == "" && form_in_password_confirm == "" && form_in_password == form_in_password_confirm) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkPassword : form_in_password and form_in_password_confirm : ", "!="); check_alert = "กรุณากรอก Password and Confirm Password"; } else if (form_in_password == "" && form_in_password_confirm != "" && form_in_password != form_in_password_confirm) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkPassword : form_in_password and form_in_password_confirm : ", "!="); check_alert = "กรุณากรอก Password and Confirm Password ตรงกัน"; } else if (form_in_password != "" && form_in_password_confirm == "" && form_in_password != form_in_password_confirm) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkPassword : form_in_password and form_in_password_confirm : ", "!="); check_alert = "กรุณากรอก Password and Confirm Password ตรงกัน"; } callback(check_format_password, check_format, check_alert); }, checkStatusAll: function(data_array, callback) { var check_data_array = data_array; var check_status_all = false; var status_pass = 0; var status_error = 0; if (data_array.length) { for (var i = 0; data_array.length > i; i++) { if (data_array[i].status) { status_pass++; for (var j = 0; data_array[i].class_or_id.length > j; j++) { $inregisterPopupTypeCct.display().formPass(data_array[i].class_or_id[j]); $inregisterPopupTypeCct.display().removeClass(data_array[i].class_or_id_error[j], "error"); $inverificationPopupTypeCct.display().setCss(data_array[i].class_or_id_error[j], "opacity", 0); $inregisterPopupTypeCct.display().postVal(data_array[i].class_or_id_error[j], ""); } } else { status_error++; for (var j = 0; data_array[i].class_or_id.length > j; j++) { $inregisterPopupTypeCct.display().formError(data_array[i].class_or_id[j]); $inregisterPopupTypeCct.display().addClass(data_array[i].class_or_id_error[j], "error"); $inverificationPopupTypeCct.display().setCss(data_array[i].class_or_id_error[j], "opacity", 1); $inregisterPopupTypeCct.display().postVal(data_array[i].class_or_id_error[j], data_array[i].alert); } } } } if (status_error == 0) { check_status_all = true; } callback(check_data_array, check_status_all); }, isLength: function(form_in, callback) { var status_check = false; if (form_in.length > 1) { status_check = true; } callback(status_check); }, isSelect: function(form_in, callback) { var status_check = false; if (form_in != '0') { status_check = true; } callback(status_check); }, isEmail: function(form_in, callback) { var format_email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var output_check = format_email.test(form_in); var status_check = false; if (output_check) { status_check = true; } callback(status_check); }, isPassword: function(form_in, callback) { var status_check = false; if (form_in.length >= 6) { status_check = true; } callback(status_check); }, isMobile: function(form_in, callback) { var format_email = /^(([0-9]{8,10}))$/; var output_check = format_email.test(form_in); var status_check = false; if (output_check) { status_check = true; } callback(status_check); }, }; return check; }; $inregisterPopupTypeCct.submitRegister = function() { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : ", "submitRegister"); var form_submit = [{ class_or_id: ["#register-firstname-v1"], class_or_id_error: ["#register-error-firstname-v1"], is_function: "length", var: "", status: "", name: "ชื่อ", alert: "", }, { class_or_id: ["#register-lastname-v1"], class_or_id_error: ["#register-error-lastname-v1"], is_function: "length", var: "", status: "", name: "นามสกุล", alert: "", }, { class_or_id: ["#register-email-v1"], class_or_id_error: ["#register-error-email-v1"], is_function: "email", var: "", status: "", name: "อีเมล", alert: "", }, { class_or_id: ["#register-mobile-v1"], class_or_id_error: ["#register-error-mobile-v1"], is_function: "mobile", var: "", status: "", name: "เบอร์โทรศัพท์", alert: "", }, { class_or_id: ["#register-amwayid-v1"], class_or_id_error: ["#register-error-amwayid-v1"], is_function: "length", var: "", status: "", name: "หมายเลขประจำตัว ABO", alert: "", }, { class_or_id: ["#register-group-v1"], class_or_id_error: ["#register-error-group-v1"], is_function: "select", var: "", status: "", name: "Team", alert: "", }, { class_or_id: ["#register-password-v1", "#register-confirm-password-v1"], class_or_id_error: ["#register-error-password-v1", "#register-error-confirm-password-v1"], is_function: "password", var: "", status: "", name: "Password and Confirm Password", alert: "", }, { class_or_id: ["#register-password-v1"], class_or_id_error: ["#register-error-password-v1"], is_function: "password", var: "", status: "", name: "Password", alert: "", }, { class_or_id: ["#register-confirm-password-v1"], class_or_id_error: ["#register-error-confirm-password-v1"], is_function: "password", var: "", status: "", name: "Confirm Password", alert: "", }]; $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : form_submit.length : ", form_submit.length); for (var i = 0; form_submit.length > i; i++) { if (form_submit[i].class_or_id.length == 1) { $inregisterPopupTypeCct.check().checkFormat(form_submit[i].class_or_id[0], form_submit[i].is_function, function(form_in, check_format, check_alert) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : firstname : checkFormat : form_in : ", form_in); form_submit[i].var = form_in; $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : firstname : checkFormat : check_format : ", check_format); form_submit[i].status = check_format; $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : firstname : checkFormat : check_alert : ", check_alert); form_submit[i].alert = check_alert + form_submit[i].name; }); } else { $inregisterPopupTypeCct.check().checkPassword(form_submit[i].class_or_id[0], form_submit[i].class_or_id[1], function(form_in, check_format, check_alert) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : aboid : checkPassword : form_in : ", form_in); form_submit[i].var = form_in; $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : aboid : checkPassword : check_format : ", check_format); form_submit[i].status = check_format; $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : firstname : checkFormat : check_alert : ", check_alert); form_submit[i].alert = check_alert; }); } } /* form_submit */ $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : form_submit : ", form_submit); /* form_submit */ $inregisterPopupTypeCct.check().checkStatusAll(form_submit, function(check_data_array, check_status_all) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : checkStatusAll : check_data_array : ", check_data_array); $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : checkStatusAll : check_status_all : ", check_status_all); if (check_status_all) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : checkStatusAll : check_status_all : ", "PASS"); $inregisterPopupTypeCct.api().customerRegister(check_data_array[0].var, check_data_array[1].var, check_data_array[2].var, check_data_array[3].var, check_data_array[4].var, check_data_array[5].var, check_data_array[6].var, function(check_ok) { $inregisterPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : verification : check_ok : ", check_ok); if (check_ok) { $inregisterPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : verification : check_ok : ", "OK"); $inregisterPopupTypeCct.close(); } }); } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : checkStatusAll : check_status_all : ", "ERROR"); } }); }; $inregisterPopupTypeCct.open = function() { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : ", " open"); $inregisterPopupTypeCct.display().reset(); $inregisterPopupTypeCct.api().currentData(function(get_current_data, check_ok) { $inregisterPopupTypeCct.display().postVal("#register-group-v1", ""); $inregisterPopupTypeCct.display().postAppend("#register-group-v1", ''); $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : get_current_data : ", get_current_data); $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check_ok : ", check_ok); if (check_ok) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : currentData : ", " PASS "); if (get_current_data.data.customer_group_array.length) { for (var i = 0; get_current_data.data.customer_group_array.length > i; i++) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : for : get_current_data.data.customer_group_array[i] : ", get_current_data.data.customer_group_array[i]); $inregisterPopupTypeCct.display().postAppend("#register-group-v1", ''); } } } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : currentData : ", " ERROR "); } }); $inregisterPopupTypeCct.display().addClass(".register_overlay", "is_open"); $inregisterPopupTypeCct.display().contronlClass('html', { 'overflow-y': 'scroll', 'overflow': 'hidden' }); $inregisterPopupTypeCct.display().contronlClass('body', { 'overflow': 'hidden', 'position': 'relative' }); var timeOpen = setTimeout(function() { $inregisterPopupTypeCct.display().addClass(".register.from_background", "is_open"); }, 100); $(document).keypress(function(output) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : keypress : output : ", output); var keyCode = (output.keyCode ? output.keyCode : output.which); $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : keypress : keyCode : ", keyCode); if (keyCode == '13') { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : keypress : output : keyCode : ", "ENTER"); $inregisterPopupTypeCct.submitRegister(); } }); }; $inregisterPopupTypeCct.close = function() { $inverificationPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : ", " close"); $inregisterPopupTypeCct.display().removeClass(".register_overlay", "is_open"); $inregisterPopupTypeCct.display().removeClass(".register.from_background", "is_open"); $inregisterPopupTypeCct.display().contronlClass('html', { 'overflow-y': 'unset', 'overflow': 'unset' }); $inregisterPopupTypeCct.display().contronlClass('body', { 'overflow': 'auto', 'position': 'relative' }); }; $inregisterPopupTypeCct.registerComplete = function() { $inregisterPopupTypeCct.display().removeClass(".register_overlay", "is_open"); $inregisterPopupTypeCct.display().removeClass(".register.from_background", "is_open"); $inregisterPopupTypeCct.display().addClass(".register_vCct_done.register_overlay", "active"); $inregisterPopupTypeCct.display().addClass(".register_vCct_done .register_done.from_background", "is_open"); }; $inregisterPopupTypeCct.closeRegisterComplete = function() { $inregisterPopupTypeCct.display().removeClass(".register_vCct_done.register_overlay", "active"); $inregisterPopupTypeCct.display().removeClass(".register_vCct_done .register_done.from_background", "is_open"); }; $inregisterPopupTypeCct.toHome = function() { $inregisterPopupTypeCct.closeRegisterComplete(); $inregisterPopupTypeCct.close(); }; $inregisterPopupTypeCct.toLogin = function() { $inregisterPopupTypeCct.closeRegisterComplete(); $inregisterPopupTypeCct.close(); $inloginPopupTypeCct.open(); };/* Cart displat at right side of page */ var $inregisterPopupTypeElc = {}; /* params */ $inregisterPopupTypeElc.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentRegisterTypeElc/"; $inregisterPopupTypeElc.templateRoot = 'root.php'; $inregisterPopupTypeElc.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inregisterPopupTypeElc.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inregisterPopupTypeElc.install = function(shopId, customBuild) { /* dont install in (checkout, register) */ this.templateRoot = 'root.php'; $.get($inregisterPopupTypeElc.path + 'componentRegisterTypeElc.css', function(response) { $('head').append(''); }); $.get($inregisterPopupTypeElc.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inregisterPopupTypeElc.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inregisterPopupTypeElc.api = GURL.base_api_url(); /* Install */ /* register model */ $inregisterPopupTypeElc.register = { firstname: '', lastname: '', bandcode: '', address: '', province: '0', amphoe: '0', tambon: '0', postel: '', email: '', idnumber: '', mobile: '', password: '', pressing: false, errore_mail: false, errore_password: false, }; $inregisterPopupTypeElc.error = { firstnameExist: false, lastnameExist: false, bandcodeExist: false, addressExist: false, provinceExist: false, amphoeExist: false, tambonExist: false, postelExist: false, emailExist: false, idnumberExist: false, mobileExist: false, firstname: false, lastname: false, bandcode: false, address: false, province: false, amphoe: false, tambon: false, postel: false, email: false, idnumber: false, mobile: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* register model */ /* API LOCATION */ $inregisterPopupTypeElc.getLocation = function(type, location_id, cur_page, per_page, txt_sortby, search, callback) { var dataLocation = []; var option = { 'search': search }; var dataSend = { 'txt_location_type_id': type, 'txt_parent_id': location_id, 'cur_page': cur_page, 'per_page': per_page, 'txt_sortby': txt_sortby, 'txt_filter_json': JSON.stringify(option) }; console.log("$inregisterPopupTypeElc : getLocation : dataSend : ", dataSend); GAEAPI.get('location/lists', dataSend).then(function(output) { var getLocationTime = setTimeout(function() { window.clearTimeout(getLocationTime); console.log("$inregisterPopupTypeElc : getLocation : output : ", output); if (output.ok == 1) { dataLocation = output.data.dataList; } callback(dataLocation); }, 100); }); }; $inregisterPopupTypeElc.getLocationId = function(location_id, callback) { var dataLocationId = []; var dataSend = { 'txt_location_id': location_id, }; console.log("$inregisterPopupTypeElc : getLocation : dataSend : ", dataSend); GAEAPI.get('location/id', dataSend).then(function(output) { var getLocationIdTime = setTimeout(function() { window.clearTimeout(getLocationIdTime); console.log("$inregisterPopupTypeElc : getLocation : output : ", output); if (output.ok == 1) { dataLocationId = output.data; } callback(dataLocationId); }, 100); }); }; $inregisterPopupTypeElc.getLocationListsId = function(type, select_value, select_value_post) { console.log("$inregisterPopupTypeElc : getLocationListsId : type : ", type); console.log("$inregisterPopupTypeElc : getLocationListsId : select_value : ", select_value); console.log("$inregisterPopupTypeElc : getLocationListsId : select_value_post : ", select_value_post); var province_id = parseInt($(select_value).val()); console.log("$inregisterPopupTypeElc : getLocationListsId : select_value : ", $(select_value).val()); console.log("$inregisterPopupTypeElc : getLocationListsId : province_id : ", province_id); if (province_id != 0) { $inregisterPopupTypeElc.getLocation(type, province_id, 1, 200, '', '', function(dataLocation) { for (var i = 0; i < dataLocation.length; i++) { console.log("$inregisterPopupTypeElc : getLocationListsId : for : dataLocation[" + i + "] : ", dataLocation[i]); $(select_value_post).append(''); } }); } if (type == 3) { var css_id = [{ css_in: '#register-amphoe-v1', value_in: '0', value_in_text: 'เลือก Amphoe', }, { css_in: '#register-tambon-v1', value_in: '0', value_in_text: 'เลือก Tambon', }, { css_in: '#register-postel-v1', value_in: '0', value_in_text: 'เลือก Postel', }]; for (var i = 0; i < css_id.length; i++) { console.log("$inregisterPopupTypeElc : getLocationListsId : for : css_id[" + i + "] : ", css_id[i]); $inregisterPopupTypeElc.validateRegister().resetLocation(css_id[i].css_in); $(css_id[i].css_in).append(''); } } else if (type == 4) { var css_id = [{ css_in: '#register-tambon-v1', value_in: '0', value_in_text: 'เลือก Tambon', }, { css_in: '#register-postel-v1', value_in: '0', value_in_text: 'เลือก Postel', }]; for (var i = 0; i < css_id.length; i++) { console.log("$inregisterPopupTypeElc : getLocationListsId : for : css_id[" + i + "] : ", css_id[i]); $inregisterPopupTypeElc.validateRegister().resetLocation(css_id[i].css_in); $(css_id[i].css_in).append(''); } } }; $inregisterPopupTypeElc.getLocationPostel = function(select_value) { console.log("$inregisterPopupTypeElc : getLocationPostel : select_value : ", select_value); var postel = parseInt($(select_value).val()); console.log("$inregisterPopupTypeElc : getLocationId : select_value : ", $(select_value).val()); console.log("$inregisterPopupTypeElc : getLocationId : postel : ", postel); if (postel != 0) { $inregisterPopupTypeElc.getLocationId(postel, function(dataLocationId) { console.log("$inregisterPopupTypeElc : getLocationId : dataLocationId.location_postcode : ", dataLocationId.location_postcode); $("#register-postel-v1").val(dataLocationId.location_postcode); }); } }; /* API LOCATION */ /* validateRegister */ $inregisterPopupTypeElc.validateRegister = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inregisterPopupTypeElc.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, getVal: function(cssID) { return $(cssID).val(); }, focusFirstname: function() { $inregisterPopupTypeElc.error.firstname = false; $inregisterPopupTypeElc.error.firstnameExist = false; $('#register-firstname-v1').css('border', ''); }, focusLastname: function() { $inregisterPopupTypeElc.error.lastname = false; $inregisterPopupTypeElc.error.lastnameExist = false; $('#register-lastname-v1').css('border', ''); }, focusBandcode: function() { $inregisterPopupTypeElc.error.bandcode = false; $inregisterPopupTypeElc.error.bandcodeExist = false; $('#register-bandcode-v1').css('border', ''); }, focusAddress: function() { $inregisterPopupTypeElc.error.address = false; $inregisterPopupTypeElc.error.addressExist = false; $('#register-address-v1').css('border', ''); }, focusProvince: function() { $inregisterPopupTypeElc.error.province = false; $inregisterPopupTypeElc.error.provinceExist = false; $('#register-province-v1').css('border', ''); }, focusAmphoe: function() { $inregisterPopupTypeElc.error.amphoe = false; $inregisterPopupTypeElc.error.amphoeExist = false; $('#register-amphoe-v1').css('border', ''); }, focusTambon: function() { $inregisterPopupTypeElc.error.tambon = false; $inregisterPopupTypeElc.error.tambonExist = false; $('#register-tambon-v1').css('border', ''); }, focusPostel: function() { $inregisterPopupTypeElc.error.postel = false; $inregisterPopupTypeElc.error.postelExist = false; $('#register-postel-v1').css('border', ''); }, focusEmail: function() { $inregisterPopupTypeElc.error.email = false; $inregisterPopupTypeElc.error.emailExist = false; $('#register-email-v1').css('border', ''); }, focusIdnumber: function() { $inregisterPopupTypeElc.error.idnumber = false; $inregisterPopupTypeElc.error.idnumberExist = false; $('#register-idnumber-v1').css('border', ''); }, focusBobile: function() { $inregisterPopupTypeElc.error.mobile = false; $inregisterPopupTypeElc.error.mobileExist = false; $('#register-mobile-v1').css('border', ''); }, focusPassword: function() { $inregisterPopupTypeElc.error_password = false; $inregisterPopupTypeElc.error.wrong_password = false; $('#register-password-v1').css('border', ''); }, firstname: function() { var v = $('#register-firstname-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isFirstname(v, true); console.log("firstname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().firstnameInputNullError(); $inregisterPopupTypeElc.error_firstname = false; $inregisterPopupTypeElc.error_firstnameExist = false; return false; } else { if (v.length > 0 && !valid) { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().firstnameInputError(); $inregisterPopupTypeElc.error_firstname = true; return false; } else if (v.length > 0 && valid) { $inregisterPopupTypeElc.validateRegister().firstnameOk(); return true; } } }, lastname: function() { var v = $('#register-lastname-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isLastname(v, true); console.log("lastname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().lastnameInputNullError(); $inregisterPopupTypeElc.error_lastname = false; $inregisterPopupTypeElc.error_lastnameExist = false; return false; } else { if (v.length > 0 && valid) { $inregisterPopupTypeElc.validateRegister().lastnameOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().lastnameInputError(); $inregisterPopupTypeElc.error_lastname = true; return false; } } }, bandcode: function() { var v = $('#register-bandcode-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isBandcode(v); console.log("inregisterPopupTypeElc : bandcode : v : ", v); console.log("inregisterPopupTypeElc : bandcode : valid : ", valid); if (valid) { $inregisterPopupTypeElc.validateRegister().bandcodeOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().bandcodeInputNullError(); return false; } }, address: function() { var v = $('#register-address-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isAddress(v); console.log("inregisterPopupTypeElc : address : v : ", v); console.log("inregisterPopupTypeElc : address : valid : ", valid); if (valid) { $inregisterPopupTypeElc.validateRegister().addressOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().addressInputNullError(); return false; } }, province: function() { var v = $('#register-province-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isProvince(v); console.log("inregisterPopupTypeElc : province : v : ", v); console.log("inregisterPopupTypeElc : province : valid : ", valid); if (valid) { $inregisterPopupTypeElc.validateRegister().provinceOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().provinceInputNullError(); return false; } }, amphoe: function() { var v = $('#register-amphoe-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isAmphoe(v); console.log("inregisterPopupTypeElc : amphoe : v : ", v); console.log("inregisterPopupTypeElc : amphoe : valid : ", valid); if (valid) { $inregisterPopupTypeElc.validateRegister().amphoeOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().amphoeInputNullError(); return false; } }, tambon: function() { var v = $('#register-tambon-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isTambon(v); console.log("inregisterPopupTypeElc : tambon : v : ", v); console.log("inregisterPopupTypeElc : tambon : valid : ", valid); if (valid) { $inregisterPopupTypeElc.validateRegister().tambonOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().tambonInputNullError(); return false; } }, postel: function() { var v = $('#register-postel-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isAddress(v); console.log("inregisterPopupTypeElc : postel : v : ", v); console.log("inregisterPopupTypeElc : postel : valid : ", valid); if (valid) { $inregisterPopupTypeElc.validateRegister().postelOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().postelInputNullError(); return false; } }, email: function() { var v = $('#register-email-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isEmail(v); console.log("inregisterPopupTypeElc : email : v : ", v); console.log("inregisterPopupTypeElc : email : valid : ", valid); if (valid) { $inregisterPopupTypeElc.validateRegister().emailOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().emailInputNullError(); return false; } }, idnumber: function() { var v = $('#register-idnumber-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isIdnumber(v); console.log("inregisterPopupTypeElc : idnumber : v : ", v); console.log("inregisterPopupTypeElc : idnumber : valid : ", valid); if (valid) { $inregisterPopupTypeElc.validateRegister().idnumberOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().idnumberInputNullError(); return false; } }, mobile: function() { var v = $('#register-mobile-v1').val(); var t = this; var valid = $inregisterPopupTypeElc.helper.isMobile(v); console.log("inregisterPopupTypeElc : mobile : v : ", v); console.log("inregisterPopupTypeElc : mobile : valid : ", valid); if (valid) { $inregisterPopupTypeElc.validateRegister().mobileOk(); return true; } else { $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().mobileInputNullError(); return false; } }, firstnameOk: function() { $('#register-firstname-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().firstnameInputOk(); }, lastnameOk: function() { $('#register-lastname-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().lastnameInputOk(); }, bandcodeOk: function() { $('#register-bandcode-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().bandcodeInputOk(); }, addressOk: function() { $('#register-address-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().addressInputOk(); }, provinceOk: function() { $('#register-province-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().provinceInputOk(); }, amphoeOk: function() { $('#register-amphoe-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().amphoeInputOk(); }, tambonOk: function() { $('#register-tambon-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().tambonInputOk(); }, postelOk: function() { $('#register-postel-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().postelInputOk(); }, emailOk: function() { $('#register-email-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().emailInputOk(); }, idnumberOk: function() { $('#register-idnumber-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().idnumberInputOk(); }, mobileOk: function() { $('#register-mobile-v1').css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().mobileInputOk(); }, firstnameInputOk: function() { $("#register-error-firstname-v1").removeClass("error"); $("#register-error-firstname-v1").css('opacity', 0); }, lastnameInputOk: function() { $("#register-error-lastname-v1").removeClass("error"); $("#register-error-lastname-v1").css('opacity', 0); }, bandcodeInputOk: function() { $("#register-error-bandcode-v1").removeClass("error"); $("#register-error-bandcode-v1").css('opacity', 0); }, addressInputOk: function() { $("#register-error-address-v1").removeClass("error"); $("#register-error-address-v1").css('opacity', 0); }, provinceInputOk: function() { $("#register-error-province-v1").removeClass("error"); $("#register-error-province-v1").css('opacity', 0); }, amphoeInputOk: function() { $("#register-error-amphoe-v1").removeClass("error"); $("#register-error-amphoe-v1").css('opacity', 0); }, tambonInputOk: function() { $("#register-error-tambon-v1").removeClass("error"); $("#register-error-tambon-v1").css('opacity', 0); }, postelInputOk: function() { $("#register-error-postel-v1").removeClass("error"); $("#register-error-postel-v1").css('opacity', 0); }, emailInputOk: function() { $("#register-error-email-v1").removeClass("error"); $("#register-error-email-v1").css('opacity', 0); }, idnumberInputOk: function() { $("#register-error-idnumber-v1").removeClass("error"); $("#register-error-idnumber-v1").css('opacity', 0); }, mobileInputOk: function() { $("#register-error-mobile-v1").removeClass("error"); $("#register-error-mobile-v1").css('opacity', 0); }, firstnameError: function() { $("#register-firstname-v1").css('border', '2px solid red'); }, lastnameError: function() { $("#register-lastname-v1").css('border', '2px solid red'); }, bandcodeError: function() { $("#register-bandcode-v1").css('border', '2px solid red'); }, addressError: function() { $("#register-address-v1").css('border', '2px solid red'); }, provinceError: function() { $("#register-province-v1").css('border', '2px solid red'); }, amphoeError: function() { $("#register-amphoe-v1").css('border', '2px solid red'); }, tambonError: function() { $("#register-tambon-v1").css('border', '2px solid red'); }, postelError: function() { $("#register-postel-v1").css('border', '2px solid red'); }, emailError: function() { $("#register-email-v1").css('border', '2px solid red'); }, idnumberError: function() { $("#register-idnumber-v1").css('border', '2px solid red'); }, mobileError: function() { $("#register-mobile-v1").css('border', '2px solid red'); }, firstnameInputError: function() { $inregisterPopupTypeElc.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputError: function() { $inregisterPopupTypeElc.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, bandcodeInputError: function() { $inregisterPopupTypeElc.validateRegister().lastnameError(); $("#register-error-bandcode-v1").addClass("error"); $("#register-error-bandcode-v1").css('opacity', 1).html('กรุณาใส่รหัสกลุ่มแบนด์ที่เคยเดินทาง'); }, addressInputError: function() { $inregisterPopupTypeElc.validateRegister().addressError(); $("#register-error-address-v1").addClass("error"); $("#register-error-address-v1").css('opacity', 1).html('กรุณาใส่ที่อยู่'); }, provinceInputError: function() { $inregisterPopupTypeElc.validateRegister().addressError(); $("#register-error-province-v1").addClass("error"); $("#register-error-province-v1").css('opacity', 1).html('กรุณาเลือกจังหวัด'); }, amphoeInputError: function() { $inregisterPopupTypeElc.validateRegister().addressError(); $("#register-error-amphoe-v1").addClass("error"); $("#register-error-amphoe-v1").css('opacity', 1).html('กรุณาเลือกอำเภอ'); }, tambonInputError: function() { $inregisterPopupTypeElc.validateRegister().addressError(); $("#register-error-tambon-v1").addClass("error"); $("#register-error-tambon-v1").css('opacity', 1).html('กรุณาเลือกตำบล'); }, postelInputError: function() { $inregisterPopupTypeElc.validateRegister().postelError(); $("#register-error-postel-v1").addClass("error"); $("#register-error-postel-v1").css('opacity', 1).html('กรุณาใส่รหัสไปรษณีย์'); }, emailInputRepeatedly: function() { $inregisterPopupTypeElc.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('อีเมลนี้มีการลงทะเบียนเป็นสมาชิกแล้ว Email already exists'); }, idnumberInputError: function() { $inregisterPopupTypeElc.validateRegister().lastnameError(); $("#register-error-idnumber-v1").addClass("error"); $("#register-error-idnumber-v1").css('opacity', 1).html('กรุณาใส่เลขประจำตัวประชาชน'); }, mobileInputError: function() { $inregisterPopupTypeElc.validateRegister().lastnameError(); $("#register-error-mobile-v1").addClass("error"); $("#register-error-mobile-v1").css('opacity', 1).html('กรุณาใส่เบอร์โทรศัพท์'); }, passwordInputRepeatedly: function() { $("#register-password-v1").css('border', '1px solid #dddddd'); }, emailInputError: function() { $inregisterPopupTypeElc.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, firstnameInputNullError: function() { $inregisterPopupTypeElc.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); // $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputNullError: function() { $inregisterPopupTypeElc.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); // $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, bandcodeInputNullError: function() { $inregisterPopupTypeElc.validateRegister().bandcodeError(); $("#register-error-bandcode-v1").addClass("error"); // $("#register-error-bandcode-v1").css('opacity', 1).html('กรุณาใส่รหัสรหัสกลุ่มแบนด์ที่เคยเดินทาง'); }, addressInputNullError: function() { $inregisterPopupTypeElc.validateRegister().addressError(); $("#register-error-address-v1").addClass("error"); // $("#register-error-address-v1").css('opacity', 1).html('กรุณาใส่ที่อยู่ '); }, provinceInputNullError: function() { $inregisterPopupTypeElc.validateRegister().provinceError(); $("#register-error-province-v1").addClass("error"); // $("#register-error-province-v1").css('opacity', 1).html('กรุณาเลือกจังหวัด'); }, amphoeInputNullError: function() { $inregisterPopupTypeElc.validateRegister().amphoeError(); $("#register-error-amphoe-v1").addClass("error"); // $("#register-error-amphoe-v1").css('opacity', 1).html('กรุณาเลือกอำเภอ'); }, tambonInputNullError: function() { $inregisterPopupTypeElc.validateRegister().tambonError(); $("#register-error-tambon-v1").addClass("error"); // $("#register-error-tambon-v1").css('opacity', 1).html('กรุณาเลือกตำบล'); }, postelInputNullError: function() { $inregisterPopupTypeElc.validateRegister().postelError(); $("#register-error-postel-v1").addClass("error"); // $("#register-error-postel-v1").css('opacity', 1).html('กรุณาใส่รหัสไปรษณีย์ '); }, emailInputNullError: function() { $inregisterPopupTypeElc.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); // $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, idnumberInputNullError: function() { $inregisterPopupTypeElc.validateRegister().idnumberError(); $("#register-error-idnumber-v1").addClass("error"); // $("#register-error-idnumber-v1").css('opacity', 1).html('กรุณาใส่เลขประจำตัวประชาชน'); }, mobileInputNullError: function() { $inregisterPopupTypeElc.validateRegister().mobileError(); $("#register-error-mobile-v1").addClass("error"); // $("#register-error-mobile-v1").css('opacity', 1).html('กรุณาใส่เบอร์โทรศัพท์'); }, password: function() { var v = $('#register-password-v1').val(); if (v.length <= 0) { $inregisterPopupTypeElc.validateRegister().passwordInputNullError(); $inregisterPopupTypeElc.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inregisterPopupTypeElc.error_password = false; $inregisterPopupTypeElc.validateRegister().passwordOk(); return true; } else if (v.length > 0 && v.length < 6) { $inregisterPopupTypeElc.error_password = true; $inregisterPopupTypeElc.shake(); $inregisterPopupTypeElc.validateRegister().passwordInputError(); return false; } }, passwordOk: function() { $("#register-password-v1").css('border', '2px solid green'); $inregisterPopupTypeElc.validateRegister().passwordInputOk(); }, passwordInputOk: function() { $("#register-error-password-v1").removeClass("error"); $("#register-error-password-v1").css('opacity', 0); }, passwordError: function() { $("#register-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inregisterPopupTypeElc.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); $("#register-error-password-v1").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputNullError: function() { $inregisterPopupTypeElc.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); // $("#register-error-password-v1").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetFirstname: function() { $("#register-firstname-v1").css('border', ''); $("#register-firstname-v1").val(''); $("#register-error-firstname-v1").css('opacity', 0); }, resetLastname: function() { $("#register-lastname-v1").css('border', ''); $("#register-lastname-v1").val(''); $("#register-error-lastname-v1").css('opacity', 0); }, resetBandcode: function() { $("#register-bandcode-v1").css('border', ''); $("#register-bandcode-v1").val(''); $("#register-error-bandcode-v1").css('opacity', 0); }, resetAddress: function() { $("#register-address-v1").css('border', ''); $("#register-address-v1").val(''); $("#register-error-address-v1").css('opacity', 0); }, resetProvince: function() { $("#register-province-v1").css('border', ''); $("#register-province-v1").val(0); $("#register-error-province-v1").css('opacity', 0); }, resetAmphoe: function() { $("#register-amphoe-v1").css('border', ''); $("#register-amphoe-v1").val(0); $("#register-error-amphoe-v1").css('opacity', 0); }, resetTambon: function() { $("#register-tambon-v1").css('border', ''); $("#register-tambon-v1").val(0); $("#register-error-tambon-v1").css('opacity', 0); }, resetPostel: function() { $("#register-postel-v1").css('border', ''); $("#register-postel-v1").val(''); $("#register-error-postel-v1").css('opacity', 0); }, resetEmail: function() { $("#register-email-v1").css('border', ''); $("#register-email-v1").val(''); $("#register-error-email-v1").css('opacity', 0); }, resetIdnumber: function() { $("#register-idnumber-v1").css('border', ''); $("#register-idnumber-v1").val(''); $("#register-error-idnumber-v1").css('opacity', 0); }, resetBobile: function() { $("#register-mobile-v1").css('border', ''); $("#register-mobile-v1").val(''); $("#register-error-mobile-v1").css('opacity', 0); }, resetPassword: function() { $("#register-password-v1").css('border', ''); $("#register-password-v1").val(''); $("#register-error-password-v1").css('opacity', 0); }, resetLocation: function(css_id) { $(css_id).html(''); }, reset: function() { $inregisterPopupTypeElc.validateRegister().resetFirstname(); $inregisterPopupTypeElc.validateRegister().resetLastname(); $inregisterPopupTypeElc.validateRegister().resetBandcode(); $inregisterPopupTypeElc.validateRegister().resetAddress(); $inregisterPopupTypeElc.validateRegister().resetProvince(); $inregisterPopupTypeElc.validateRegister().resetAmphoe(); $inregisterPopupTypeElc.validateRegister().resetTambon(); $inregisterPopupTypeElc.validateRegister().resetPostel(); $inregisterPopupTypeElc.validateRegister().resetEmail(); $inregisterPopupTypeElc.validateRegister().resetIdnumber(); $inregisterPopupTypeElc.validateRegister().resetBobile(); $inregisterPopupTypeElc.validateRegister().resetPassword(); }, }; return promise; }; /* validateRegister */ /* load html */ $inregisterPopupTypeElc.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inregisterPopupTypeElc.whenOnLoad = function(shopId) {}; $inregisterPopupTypeElc.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isFormat: function(format, data) { return format.test(data); }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isFirstname: function(firstname) { if (firstname.length > 1) { return true; } else { return false; } }, isLastname: function(lastname) { if (lastname.length > 1) { return true; } else { return false; } }, isBandcode: function(bandcode) { var re = /^((([a-zA-Z]{2})+[0-9]{10}))$/; var bandcode = re.test(bandcode); if (bandcode) { return true; } else { return false; } }, isAddress: function(address) { if (address.length) { return true; } else { return false; } }, isProvince: function(province) { if (province != '0') { return true; } else { return false; } }, isAmphoe: function(amphoe) { if (amphoe != '0') { return true; } else { return false; } }, isTambon: function(tambon) { if (tambon != '0') { return true; } else { return false; } }, isPostel: function(postel) { if (postel.length) { return true; } else { return false; } }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isIdnumber: function(idnumber) { var re = /^(([0-9]{13}))$/; var result = re.test(idnumber); if (result) { return true; } else { return false; } }, isMobile: function(mobile) { var re = /^(([0-9]{8,10}))$/; var result = re.test(mobile); if (result) { return true; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.register_vElc_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.register_vElc_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, registerDone: function() { var load = $('.register_vElc_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vElc_done .register_done.from_background").addClass("is_open"); }, 100); }, registerUnDone: function() { var load = $('.register_vElc_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vElc_done .register_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitRegister */ $inregisterPopupTypeElc.submitRegister = function() { $inregisterPopupTypeElc.register.firstname = $inregisterPopupTypeElc.validateRegister().getVal('#register-firstname-v1'); $inregisterPopupTypeElc.register.lastname = $inregisterPopupTypeElc.validateRegister().getVal('#register-lastname-v1'); $inregisterPopupTypeElc.register.bandcode = $inregisterPopupTypeElc.validateRegister().getVal('#register-bandcode-v1'); $inregisterPopupTypeElc.register.address = $inregisterPopupTypeElc.validateRegister().getVal('#register-address-v1'); $inregisterPopupTypeElc.register.province = $inregisterPopupTypeElc.validateRegister().getVal('#register-province-v1'); $inregisterPopupTypeElc.register.amphoe = $inregisterPopupTypeElc.validateRegister().getVal('#register-amphoe-v1'); $inregisterPopupTypeElc.register.tambon = $inregisterPopupTypeElc.validateRegister().getVal('#register-tambon-v1'); $inregisterPopupTypeElc.register.postel = $inregisterPopupTypeElc.validateRegister().getVal('#register-postel-v1'); $inregisterPopupTypeElc.register.email = $inregisterPopupTypeElc.validateRegister().getVal('#register-email-v1'); $inregisterPopupTypeElc.register.idnumber = $inregisterPopupTypeElc.validateRegister().getVal('#register-idnumber-v1'); $inregisterPopupTypeElc.register.mobile = $inregisterPopupTypeElc.validateRegister().getVal('#register-mobile-v1'); $inregisterPopupTypeElc.register.password = $inregisterPopupTypeElc.validateRegister().getVal('#register-password-v1'); var userFirstnameValid = $inregisterPopupTypeElc.validateRegister().firstname(); var userLastnameValid = $inregisterPopupTypeElc.validateRegister().lastname(); var userBandcodeValid = $inregisterPopupTypeElc.validateRegister().bandcode(); var userAddressValid = $inregisterPopupTypeElc.validateRegister().address(); var userProvinceValid = $inregisterPopupTypeElc.validateRegister().province(); var userAmphoeValid = $inregisterPopupTypeElc.validateRegister().amphoe(); var userTambonValid = $inregisterPopupTypeElc.validateRegister().tambon(); var userPostelValid = $inregisterPopupTypeElc.validateRegister().postel(); var userEmailValid = $inregisterPopupTypeElc.validateRegister().email(); var userIdnumberValid = $inregisterPopupTypeElc.validateRegister().idnumber(); var userMobileValid = $inregisterPopupTypeElc.validateRegister().mobile(); var userPassValid = $inregisterPopupTypeElc.validateRegister().password(); console.log("submitRegister", "userFirstnameValid : ", userFirstnameValid, "userLastnameValid : ", userLastnameValid, "userBandcodeValid : ", userBandcodeValid, "userEmailValid : ", userEmailValid, "userIdnumberValid : ", userIdnumberValid, "userMobileValid : ", userMobileValid, "userPassValid : ", userPassValid); if (!userFirstnameValid || !userLastnameValid || !userBandcodeValid || !userAddressValid || !userProvinceValid || !userAmphoeValid || !userTambonValid || !userPostelValid || !userEmailValid || !userIdnumberValid || !userMobileValid || !userPassValid) { console.log("submitRegister", "return"); $inregisterPopupTypeElc.shake(); return; } $inregisterPopupTypeElc.validateRegister().checkEmail($inregisterPopupTypeElc.register.email, function(resultCheck) { console.log("submitRegister", resultCheck); if (resultCheck.ok == 0) { console.log('submitRegister true'); $inregisterPopupTypeElc.validateRegister().emailInputRepeatedly(); $inregisterPopupTypeElc.validateRegister().passwordInputRepeatedly(); } else { console.log('submitRegister false'); return $inregisterPopupTypeElc.sendSubmitRegister(false); } }); }; /* submitRegister */ /* sendSubmitRegister */ $inregisterPopupTypeElc.sendSubmitRegister = function(reCheck) { $inregisterPopupTypeElc.register.pressing = true var userFirstname = $inregisterPopupTypeElc.register.firstname; var userLastname = $inregisterPopupTypeElc.register.lastname; var userBandcode = $inregisterPopupTypeElc.register.bandcode; var userAddress = $inregisterPopupTypeElc.register.address; var userProvince = parseInt($inregisterPopupTypeElc.register.province); var userAmphoe = parseInt($inregisterPopupTypeElc.register.amphoe); var userTambon = parseInt($inregisterPopupTypeElc.register.tambon); var userPostel = $inregisterPopupTypeElc.register.postel; $inregisterPopupTypeElc.getLocationId(userProvince, function(dataLocationId) { console.log("$inregisterPopupTypeElc : sendSubmitRegister : userProvince : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); userProvince = dataLocationId.location_name; $inregisterPopupTypeElc.getLocationId(userAmphoe, function(dataLocationId) { console.log("$inregisterPopupTypeElc : sendSubmitRegister : userAmphoe : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); userAmphoe = dataLocationId.location_name; $inregisterPopupTypeElc.getLocationId(userTambon, function(dataLocationId) { console.log("$inregisterPopupTypeElc : sendSubmitRegister : userTambon : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); userTambon = dataLocationId.location_name; var userEmail = $inregisterPopupTypeElc.register.email; var userIdnumber = $inregisterPopupTypeElc.register.idnumber; var userMobile = $inregisterPopupTypeElc.register.mobile; var userPass = $inregisterPopupTypeElc.register.password; console.log("sendSubmitRegister", reCheck); if (reCheck) { /* if error : firstname */ if (userFirstname.length <= 0) { $inregisterPopupTypeElc.validateRegister().firstnameInputError(); } else { $inregisterPopupTypeElc.validateRegister().firstnameOk(); } /* if error : lastname */ if (userLastname.length <= 0) { $inregisterPopupTypeElc.validateRegister().lastnameInputError(); } else { $inregisterPopupTypeElc.validateRegister().lastnameOk(); } /* if error : userBandcode */ if (userBandcode.length <= 0) { $inregisterPopupTypeElc.validateRegister().bandcodeInputError(); } else { $inregisterPopupTypeElc.validateRegister().bandcodeOk(); } /* if error : userAddress */ if (userAddress.length <= 0) { $inregisterPopupTypeElc.validateRegister().addressInputError(); } else { $inregisterPopupTypeElc.validateRegister().addressOk(); } /* if error : userProvince */ if (userProvince.length <= 0) { $inregisterPopupTypeElc.validateRegister().provinceInputError(); } else { $inregisterPopupTypeElc.validateRegister().provinceOk(); } /* if error : userAmphoe */ if (userAmphoe.length <= 0) { $inregisterPopupTypeElc.validateRegister().amphoeInputError(); } else { $inregisterPopupTypeElc.validateRegister().amphoeOk(); } /* if error : userTambon */ if (userTambon.length <= 0) { $inregisterPopupTypeElc.validateRegister().tambonInputError(); } else { $inregisterPopupTypeElc.validateRegister().tambonOk(); } /* if error : userPostel */ if (userPostel.length <= 0) { $inregisterPopupTypeElc.validateRegister().postelInputError(); } else { $inregisterPopupTypeElc.validateRegister().postelOk(); } /* if error : user */ if (userEmail.length <= 0) { $inregisterPopupTypeElc.validateRegister().emailInputError(); } else { $inregisterPopupTypeElc.validateRegister().emailOk(); } /* if error : userIdnumber */ if (userIdnumber.length <= 0) { $inregisterPopupTypeElc.validateRegister().idnumberInputError(); } else { $inregisterPopupTypeElc.validateRegister().idnumberOk(); } /* if error : userMobile */ if (userMobile.length <= 0) { $inregisterPopupTypeElc.validateRegister().mobileInputError(); } else { $inregisterPopupTypeElc.validateRegister().mobileOk(); } /* if error : pass */ if (userPass.length <= 0) { $inregisterPopupTypeElc.validateRegister().passwordOk(); } else { $inregisterPopupTypeElc.validateRegister().passwordInputError(); } /* firstname */ if (userFirstname.length > 0 && !$inregisterPopupTypeElc.helper.isFirstname(userFirstname)) { $inregisterPopupTypeElc.error_firstname = true; } else { $inregisterPopupTypeElc.error_firstname = false; } /* lastname */ if (userLastname.length > 0 && !$inregisterPopupTypeElc.helper.isLastname(userLastname)) { $inregisterPopupTypeElc.error_lastname = true; } else { $inregisterPopupTypeElc.error_lastname = false; } /* bandcode */ if (userBandcode.length > 0 && !$inregisterPopupTypeElc.helper.isBandcode(userBandcode)) { $inregisterPopupTypeElc.error_bandcode = true; } else { $inregisterPopupTypeElc.error_bandcode = false; } /* email */ if (userEmail.length > 0 && !$inregisterPopupTypeElc.helper.isEmail(userEmail)) { $inregisterPopupTypeElc.error_email = true; } else { $inregisterPopupTypeElc.error_email = false; } /* userIdnumber */ if (userIdnumber.length > 0 && !$inregisterPopupTypeElc.helper.isIdnumber(userIdnumber)) { $inregisterPopupTypeElc.error_idnumber = true; } else { $inregisterPopupTypeElc.error_idnumber = false; } /* userMobile */ if (userMobile.length > 0 && !$inregisterPopupTypeElc.helper.isMobile(userMobile)) { $inregisterPopupTypeElc.error_mobile = true; } else { $inregisterPopupTypeElc.error_mobile = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inregisterPopupTypeElc.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inregisterPopupTypeElc.error_password = true; } console.log("sendSubmitRegister : ", "error_firstname : ", $inregisterPopupTypeElc.error_firstname, "error_lastname : ", $inregisterPopupTypeElc.error_lastname, "error_email : ", $inregisterPopupTypeElc.error_email, "error_password : ", $inregisterPopupTypeElc.error_password); if ($inregisterPopupTypeElc.error_firstname || $inregisterPopupTypeElc.error_lastname || $inregisterPopupTypeElc.error_bandcode || $inregisterPopupTypeElc.error_email || $inregisterPopupTypeElc.error_idnumber || $inregisterPopupTypeElc.error_mobile || $inregisterPopupTypeElc.error_password) { console.log("sendSubmitRegister return"); $inregisterPopupTypeElc.shake(); return; } } /* loading */ $inregisterPopupTypeElc.helper.pageLoad(); var dataSend = { 'txt_first_name': userFirstname, 'txt_last_name': userLastname, 'txt_code': userBandcode, 'txt_info_address': userAddress, 'txt_info_province': userProvince, 'txt_info_amphoe': userAmphoe, 'txt_info_tambon': userTambon, 'txt_info_postcode': userPostel, 'txt_email': userEmail, 'txt_note': userIdnumber, 'txt_phone': userMobile, 'txt_password': userPass }; console.log("sendSubmitRegister txt_email : ", dataSend); GAEAPI.post("ui/api/ui_customer_box/customer/register", dataSend).then(function(output) { console.log("sendSubmitRegister register : ", output); if (output.ok == 1) { $inregisterPopupTypeElc.close(); $inregisterPopupTypeElc.helper.pageUnLoad(); $inregisterPopupTypeElc.helper.registerDone(); GAEAPI.get('customer/logout', {}).then(function(output_logout) { if (output_logout.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); } else { $inregisterPopupTypeElc.helper.pageUnLoad(); alert("Register ผิดพลาด! กรุณาลองใหม่อีกครั้ง"); } }); }); }); }); /* loading */ }; /* sendSubmitRegister */ /* viewPassword */ $inregisterPopupTypeElc.viewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); if (t === 'password') { e.attr('type', 'text'); } else { e.attr('type', 'password'); } }; $inregisterPopupTypeElc.resetViewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); e.attr('type', 'password'); }; /* viewPassword */ $inregisterPopupTypeElc.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inregisterPopupTypeElc.isOpen = false; $inregisterPopupTypeElc.open = function() { $inregisterPopupTypeElc.resetViewPassword('register-password-v1'); $inregisterPopupTypeElc.validateRegister().reset(); $(".register_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'relative' }); timerAdjustOpen = setTimeout(function() { $(".register.from_background").addClass("is_open"); }, 100); $inregisterPopupTypeElc.getLocation(2, 231, 1, 100, '', '', function(dataLocation) { console.log("$inregisterPopupTypeElc : open : dataLocation : ", dataLocation); for (var i = 0; i < dataLocation.length; i++) { console.log("2 $inregisterPopupTypeElc : open : for : dataLocation[" + i + "] : ", dataLocation[i]); $('#register-province-v1').append(''); } }); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inregisterPopupTypeElc.submitRegister(); } }); }; /* Open */ /* Close */ $inregisterPopupTypeElc.close = function() { $(".register_overlay").removeClass("is_open"); $(".register.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inregisterPopupTypeElc.shake = function() { $(".register.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".register.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inregisterPopupTypeElc.login = function() { $inregisterPopupTypeElc.close(); $inregisterPopupTypeElc.helper.registerUnDone(); $inloginPopup.open(); } /* login */ /* toHome */ $inregisterPopupTypeElc.toHome = function() { $inregisterPopupTypeElc.helper.registerUnDone(); window.location.href = 'home'; }; /* toHome *//* Cart displat at right side of page */ var $inregisterPopupTypeGrip = {}; /* params */ $inregisterPopupTypeGrip.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentRegisterTypeGrip/"; $inregisterPopupTypeGrip.templateRoot = 'root.php'; $inregisterPopupTypeGrip.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inregisterPopupTypeGrip.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inregisterPopupTypeGrip.install = function(shopId, customBuild) { /* dont install in (checkout, register) */ this.templateRoot = 'root.php'; $.get($inregisterPopupTypeGrip.path + 'componentRegisterTypeGrip.css', function(response) { $('head').append(''); }); $.get($inregisterPopupTypeGrip.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inregisterPopupTypeGrip.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inregisterPopupTypeGrip.api = GURL.base_api_url(); /* Install */ /* register model */ $inregisterPopupTypeGrip.register = { firstname: '', lastname: '', bandcode: '', address: '', vehicle: '', province: '0', amphoe: '0', tambon: '0', postel: '', email: '', idnumber: '', mobile: '', password: '', pressing: false, errore_mail: false, errore_password: false, }; $inregisterPopupTypeGrip.error = { firstnameExist: false, lastnameExist: false, bandcodeExist: false, addressExist: false, vehicleExist: false, provinceExist: false, amphoeExist: false, tambonExist: false, postelExist: false, emailExist: false, idnumberExist: false, mobileExist: false, firstname: false, lastname: false, bandcode: false, address: false, vehicle: false, province: false, amphoe: false, tambon: false, postel: false, email: false, idnumber: false, mobile: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* register model */ /* API LOCATION */ $inregisterPopupTypeGrip.getLocation = function(type, location_id, cur_page, per_page, txt_sortby, search, callback) { var dataLocation = []; var option = { 'search': search }; var dataSend = { 'txt_location_type_id': type, 'txt_parent_id': location_id, 'cur_page': cur_page, 'per_page': per_page, 'txt_sortby': txt_sortby, 'txt_filter_json': JSON.stringify(option) }; console.log("$inregisterPopupTypeGrip : getLocation : dataSend : ", dataSend); GAEAPI.get('location/lists', dataSend).then(function(output) { var getLocationTime = setTimeout(function() { window.clearTimeout(getLocationTime); console.log("$inregisterPopupTypeGrip : getLocation : output : ", output); if (output.ok == 1) { dataLocation = output.data.dataList; } callback(dataLocation); }, 100); }); }; $inregisterPopupTypeGrip.getLocationId = function(location_id, callback) { var dataLocationId = []; var dataSend = { 'txt_location_id': location_id, }; console.log("$inregisterPopupTypeGrip : getLocation : dataSend : ", dataSend); GAEAPI.get('location/id', dataSend).then(function(output) { var getLocationIdTime = setTimeout(function() { window.clearTimeout(getLocationIdTime); console.log("$inregisterPopupTypeGrip : getLocation : output : ", output); if (output.ok == 1) { dataLocationId = output.data; } callback(dataLocationId); }, 100); }); }; $inregisterPopupTypeGrip.getLocationListsId = function(type, select_value, select_value_post) { console.log("$inregisterPopupTypeGrip : getLocationListsId : type : ", type); console.log("$inregisterPopupTypeGrip : getLocationListsId : select_value : ", select_value); console.log("$inregisterPopupTypeGrip : getLocationListsId : select_value_post : ", select_value_post); var province_id = parseInt($(select_value).val()); console.log("$inregisterPopupTypeGrip : getLocationListsId : select_value : ", $(select_value).val()); console.log("$inregisterPopupTypeGrip : getLocationListsId : province_id : ", province_id); if (province_id != 0) { $inregisterPopupTypeGrip.getLocation(type, province_id, 1, 200, '', '', function(dataLocation) { for (var i = 0; i < dataLocation.length; i++) { console.log("$inregisterPopupTypeGrip : getLocationListsId : for : dataLocation[" + i + "] : ", dataLocation[i]); $(select_value_post).append(''); } }); } if (type == 3) { var css_id = [{ css_in: '#register-amphoe-v1', value_in: '0', value_in_text: 'เลือก Amphoe', }, { css_in: '#register-tambon-v1', value_in: '0', value_in_text: 'เลือก Tambon', }, { css_in: '#register-postel-v1', value_in: '0', value_in_text: 'เลือก Postel', }]; for (var i = 0; i < css_id.length; i++) { console.log("$inregisterPopupTypeGrip : getLocationListsId : for : css_id[" + i + "] : ", css_id[i]); $inregisterPopupTypeGrip.validateRegister().resetLocation(css_id[i].css_in); $(css_id[i].css_in).append(''); } } else if (type == 4) { var css_id = [{ css_in: '#register-tambon-v1', value_in: '0', value_in_text: 'เลือก Tambon', }, { css_in: '#register-postel-v1', value_in: '0', value_in_text: 'เลือก Postel', }]; for (var i = 0; i < css_id.length; i++) { console.log("$inregisterPopupTypeGrip : getLocationListsId : for : css_id[" + i + "] : ", css_id[i]); $inregisterPopupTypeGrip.validateRegister().resetLocation(css_id[i].css_in); $(css_id[i].css_in).append(''); } } }; $inregisterPopupTypeGrip.getLocationPostel = function(select_value) { console.log("$inregisterPopupTypeGrip : getLocationPostel : select_value : ", select_value); var postel = parseInt($(select_value).val()); console.log("$inregisterPopupTypeGrip : getLocationId : select_value : ", $(select_value).val()); console.log("$inregisterPopupTypeGrip : getLocationId : postel : ", postel); if (postel != 0) { $inregisterPopupTypeGrip.getLocationId(postel, function(dataLocationId) { console.log("$inregisterPopupTypeGrip : getLocationId : dataLocationId.location_postcode : ", dataLocationId.location_postcode); $("#register-postel-v1").val(dataLocationId.location_postcode); }); } }; /* API LOCATION */ /* validateRegister */ $inregisterPopupTypeGrip.validateRegister = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inregisterPopupTypeGrip.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, getVal: function(cssID) { return $(cssID).val(); }, focusFirstname: function() { $inregisterPopupTypeGrip.error.firstname = false; $inregisterPopupTypeGrip.error.firstnameExist = false; $('#register-firstname-v1').css('border', ''); }, focusLastname: function() { $inregisterPopupTypeGrip.error.lastname = false; $inregisterPopupTypeGrip.error.lastnameExist = false; $('#register-lastname-v1').css('border', ''); }, focusBandcode: function() { $inregisterPopupTypeGrip.error.bandcode = false; $inregisterPopupTypeGrip.error.bandcodeExist = false; $('#register-bandcode-v1').css('border', ''); }, focusAddress: function() { $inregisterPopupTypeGrip.error.address = false; $inregisterPopupTypeGrip.error.addressExist = false; $('#register-address-v1').css('border', ''); }, focusVehicle: function() { $inregisterPopupTypeGrip.error.address = false; $inregisterPopupTypeGrip.error.addressExist = false; $('#register-vehicle-v1').css('border', ''); }, focusProvince: function() { $inregisterPopupTypeGrip.error.province = false; $inregisterPopupTypeGrip.error.provinceExist = false; $('#register-province-v1').css('border', ''); }, focusAmphoe: function() { $inregisterPopupTypeGrip.error.amphoe = false; $inregisterPopupTypeGrip.error.amphoeExist = false; $('#register-amphoe-v1').css('border', ''); }, focusTambon: function() { $inregisterPopupTypeGrip.error.tambon = false; $inregisterPopupTypeGrip.error.tambonExist = false; $('#register-tambon-v1').css('border', ''); }, focusPostel: function() { $inregisterPopupTypeGrip.error.postel = false; $inregisterPopupTypeGrip.error.postelExist = false; $('#register-postel-v1').css('border', ''); }, focusEmail: function() { $inregisterPopupTypeGrip.error.email = false; $inregisterPopupTypeGrip.error.emailExist = false; $('#register-email-v1').css('border', ''); }, focusIdnumber: function() { $inregisterPopupTypeGrip.error.idnumber = false; $inregisterPopupTypeGrip.error.idnumberExist = false; $('#register-idnumber-v1').css('border', ''); }, focusBobile: function() { $inregisterPopupTypeGrip.error.mobile = false; $inregisterPopupTypeGrip.error.mobileExist = false; $('#register-mobile-v1').css('border', ''); }, focusPassword: function() { $inregisterPopupTypeGrip.error_password = false; $inregisterPopupTypeGrip.error.wrong_password = false; $('#register-password-v1').css('border', ''); }, firstname: function() { var v = $('#register-firstname-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isFirstname(v, true); console.log("firstname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().firstnameInputNullError(); $inregisterPopupTypeGrip.error_firstname = false; $inregisterPopupTypeGrip.error_firstnameExist = false; return false; } else { if (v.length > 0 && !valid) { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().firstnameInputError(); $inregisterPopupTypeGrip.error_firstname = true; return false; } else if (v.length > 0 && valid) { $inregisterPopupTypeGrip.validateRegister().firstnameOk(); return true; } } }, lastname: function() { var v = $('#register-lastname-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isLastname(v, true); console.log("lastname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().lastnameInputNullError(); $inregisterPopupTypeGrip.error_lastname = false; $inregisterPopupTypeGrip.error_lastnameExist = false; return false; } else { if (v.length > 0 && valid) { $inregisterPopupTypeGrip.validateRegister().lastnameOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().lastnameInputError(); $inregisterPopupTypeGrip.error_lastname = true; return false; } } }, bandcode: function() { var v = $('#register-bandcode-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isBandcode(v); console.log("inregisterPopupTypeElc : bandcode : v : ", v); console.log("inregisterPopupTypeElc : bandcode : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().bandcodeOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().bandcodeInputNullError(); return false; } }, address: function() { var v = $('#register-address-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isAddress(v); console.log("inregisterPopupTypeElc : address : v : ", v); console.log("inregisterPopupTypeElc : address : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().addressOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().addressInputNullError(); return false; } }, vehicle: function() { var v = $('#register-vehicle-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isVehicle(v); console.log("inregisterPopupTypeElc : vehicle : v : ", v); console.log("inregisterPopupTypeElc : vehicle : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().vehicleOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().vehicleInputNullError(); return false; } }, province: function() { var v = $('#register-province-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isProvince(v); console.log("inregisterPopupTypeElc : province : v : ", v); console.log("inregisterPopupTypeElc : province : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().provinceOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().provinceInputNullError(); return false; } }, amphoe: function() { var v = $('#register-amphoe-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isAmphoe(v); console.log("inregisterPopupTypeElc : amphoe : v : ", v); console.log("inregisterPopupTypeElc : amphoe : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().amphoeOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().amphoeInputNullError(); return false; } }, tambon: function() { var v = $('#register-tambon-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isTambon(v); console.log("inregisterPopupTypeElc : tambon : v : ", v); console.log("inregisterPopupTypeElc : tambon : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().tambonOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().tambonInputNullError(); return false; } }, postel: function() { var v = $('#register-postel-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isAddress(v); console.log("inregisterPopupTypeElc : postel : v : ", v); console.log("inregisterPopupTypeElc : postel : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().postelOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().postelInputNullError(); return false; } }, email: function() { var v = $('#register-email-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isEmail(v); console.log("inregisterPopupTypeElc : email : v : ", v); console.log("inregisterPopupTypeElc : email : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().emailOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().emailInputNullError(); return false; } }, idnumber: function() { var v = $('#register-idnumber-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isIdnumber(v); console.log("inregisterPopupTypeElc : idnumber : v : ", v); console.log("inregisterPopupTypeElc : idnumber : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().idnumberOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().idnumberInputNullError(); return false; } }, mobile: function() { var v = $('#register-mobile-v1').val(); var t = this; var valid = $inregisterPopupTypeGrip.helper.isMobile(v); console.log("inregisterPopupTypeElc : mobile : v : ", v); console.log("inregisterPopupTypeElc : mobile : valid : ", valid); if (valid) { $inregisterPopupTypeGrip.validateRegister().mobileOk(); return true; } else { $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().mobileInputNullError(); return false; } }, firstnameOk: function() { $('#register-firstname-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().firstnameInputOk(); }, lastnameOk: function() { $('#register-lastname-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().lastnameInputOk(); }, bandcodeOk: function() { $('#register-bandcode-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().bandcodeInputOk(); }, addressOk: function() { $('#register-address-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().addressInputOk(); }, vehicleOk: function() { $('#register-vehicle-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().vehicleInputOk(); }, provinceOk: function() { $('#register-province-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().provinceInputOk(); }, amphoeOk: function() { $('#register-amphoe-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().amphoeInputOk(); }, tambonOk: function() { $('#register-tambon-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().tambonInputOk(); }, postelOk: function() { $('#register-postel-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().postelInputOk(); }, emailOk: function() { $('#register-email-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().emailInputOk(); }, idnumberOk: function() { $('#register-idnumber-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().idnumberInputOk(); }, mobileOk: function() { $('#register-mobile-v1').css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().mobileInputOk(); }, firstnameInputOk: function() { $("#register-error-firstname-v1").removeClass("error"); $("#register-error-firstname-v1").css('opacity', 0); }, lastnameInputOk: function() { $("#register-error-lastname-v1").removeClass("error"); $("#register-error-lastname-v1").css('opacity', 0); }, bandcodeInputOk: function() { $("#register-error-bandcode-v1").removeClass("error"); $("#register-error-bandcode-v1").css('opacity', 0); }, addressInputOk: function() { $("#register-error-address-v1").removeClass("error"); $("#register-error-address-v1").css('opacity', 0); }, vehicleInputOk: function() { $("#register-error-vehicle-v1").removeClass("error"); $("#register-error-vehicle-v1").css('opacity', 0); }, provinceInputOk: function() { $("#register-error-province-v1").removeClass("error"); $("#register-error-province-v1").css('opacity', 0); }, amphoeInputOk: function() { $("#register-error-amphoe-v1").removeClass("error"); $("#register-error-amphoe-v1").css('opacity', 0); }, tambonInputOk: function() { $("#register-error-tambon-v1").removeClass("error"); $("#register-error-tambon-v1").css('opacity', 0); }, postelInputOk: function() { $("#register-error-postel-v1").removeClass("error"); $("#register-error-postel-v1").css('opacity', 0); }, emailInputOk: function() { $("#register-error-email-v1").removeClass("error"); $("#register-error-email-v1").css('opacity', 0); }, idnumberInputOk: function() { $("#register-error-idnumber-v1").removeClass("error"); $("#register-error-idnumber-v1").css('opacity', 0); }, mobileInputOk: function() { $("#register-error-mobile-v1").removeClass("error"); $("#register-error-mobile-v1").css('opacity', 0); }, firstnameError: function() { $("#register-firstname-v1").css('border', '2px solid red'); }, lastnameError: function() { $("#register-lastname-v1").css('border', '2px solid red'); }, bandcodeError: function() { $("#register-bandcode-v1").css('border', '2px solid red'); }, addressError: function() { $("#register-address-v1").css('border', '2px solid red'); }, vehicleError: function() { $("#register-vehicle-v1").css('border', '2px solid red'); }, provinceError: function() { $("#register-province-v1").css('border', '2px solid red'); }, amphoeError: function() { $("#register-amphoe-v1").css('border', '2px solid red'); }, tambonError: function() { $("#register-tambon-v1").css('border', '2px solid red'); }, postelError: function() { $("#register-postel-v1").css('border', '2px solid red'); }, emailError: function() { $("#register-email-v1").css('border', '2px solid red'); }, idnumberError: function() { $("#register-idnumber-v1").css('border', '2px solid red'); }, mobileError: function() { $("#register-mobile-v1").css('border', '2px solid red'); }, firstnameInputError: function() { $inregisterPopupTypeGrip.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputError: function() { $inregisterPopupTypeGrip.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, bandcodeInputError: function() { $inregisterPopupTypeGrip.validateRegister().lastnameError(); $("#register-error-bandcode-v1").addClass("error"); $("#register-error-bandcode-v1").css('opacity', 1).html('กรุณาใส่รหัสกลุ่มแบนด์ที่เคยเดินทาง'); }, addressInputError: function() { $inregisterPopupTypeGrip.validateRegister().addressError(); $("#register-error-address-v1").addClass("error"); $("#register-error-address-v1").css('opacity', 1).html('กรุณาใส่ที่อยู่'); }, vehicleInputError: function() { $inregisterPopupTypeGrip.validateRegister().addressError(); $("#register-error-vehicle-v1").addClass("error"); $("#register-error-vehicle-v1").css('opacity', 1).html('กรุณาใส่ทะเบียนรถยนต์'); }, provinceInputError: function() { $inregisterPopupTypeGrip.validateRegister().addressError(); $("#register-error-province-v1").addClass("error"); $("#register-error-province-v1").css('opacity', 1).html('กรุณาเลือกจังหวัด'); }, amphoeInputError: function() { $inregisterPopupTypeGrip.validateRegister().addressError(); $("#register-error-amphoe-v1").addClass("error"); $("#register-error-amphoe-v1").css('opacity', 1).html('กรุณาเลือกอำเภอ'); }, tambonInputError: function() { $inregisterPopupTypeGrip.validateRegister().addressError(); $("#register-error-tambon-v1").addClass("error"); $("#register-error-tambon-v1").css('opacity', 1).html('กรุณาเลือกตำบล'); }, postelInputError: function() { $inregisterPopupTypeGrip.validateRegister().postelError(); $("#register-error-postel-v1").addClass("error"); $("#register-error-postel-v1").css('opacity', 1).html('กรุณาใส่รหัสไปรษณีย์'); }, emailInputRepeatedly: function() { $inregisterPopupTypeGrip.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('อีเมลนี้มีการลงทะเบียนเป็นสมาชิกแล้ว Email already exists'); }, idnumberInputError: function() { $inregisterPopupTypeGrip.validateRegister().lastnameError(); $("#register-error-idnumber-v1").addClass("error"); $("#register-error-idnumber-v1").css('opacity', 1).html('กรุณาใส่เลขประจำตัวประชาชน'); }, mobileInputError: function() { $inregisterPopupTypeGrip.validateRegister().lastnameError(); $("#register-error-mobile-v1").addClass("error"); $("#register-error-mobile-v1").css('opacity', 1).html('กรุณาใส่เบอร์โทรศัพท์'); }, passwordInputRepeatedly: function() { $("#register-password-v1").css('border', '1px solid #dddddd'); }, emailInputError: function() { $inregisterPopupTypeGrip.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, firstnameInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); // $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); // $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, bandcodeInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().bandcodeError(); $("#register-error-bandcode-v1").addClass("error"); // $("#register-error-bandcode-v1").css('opacity', 1).html('กรุณาใส่รหัสรหัสกลุ่มแบนด์ที่เคยเดินทาง'); }, addressInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().addressError(); $("#register-error-address-v1").addClass("error"); // $("#register-error-address-v1").css('opacity', 1).html('กรุณาใส่ที่อยู่ '); }, vehicleInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().vehicleError(); $("#register-error-vehicle-v1").addClass("error"); // $("#register-error-vehicle-v1").css('opacity', 1).html('กรุณาใส่ทะเบียนรถยนต์'); }, provinceInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().provinceError(); $("#register-error-province-v1").addClass("error"); // $("#register-error-province-v1").css('opacity', 1).html('กรุณาเลือกจังหวัด'); }, amphoeInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().amphoeError(); $("#register-error-amphoe-v1").addClass("error"); // $("#register-error-amphoe-v1").css('opacity', 1).html('กรุณาเลือกอำเภอ'); }, tambonInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().tambonError(); $("#register-error-tambon-v1").addClass("error"); // $("#register-error-tambon-v1").css('opacity', 1).html('กรุณาเลือกตำบล'); }, postelInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().postelError(); $("#register-error-postel-v1").addClass("error"); // $("#register-error-postel-v1").css('opacity', 1).html('กรุณาใส่รหัสไปรษณีย์ '); }, emailInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); // $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, idnumberInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().idnumberError(); $("#register-error-idnumber-v1").addClass("error"); // $("#register-error-idnumber-v1").css('opacity', 1).html('กรุณาใส่เลขประจำตัวประชาชน'); }, mobileInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().mobileError(); $("#register-error-mobile-v1").addClass("error"); // $("#register-error-mobile-v1").css('opacity', 1).html('กรุณาใส่เบอร์โทรศัพท์'); }, password: function() { var v = $('#register-password-v1').val(); if (v.length <= 0) { $inregisterPopupTypeGrip.validateRegister().passwordInputNullError(); $inregisterPopupTypeGrip.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inregisterPopupTypeGrip.error_password = false; $inregisterPopupTypeGrip.validateRegister().passwordOk(); return true; } else if (v.length > 0 && v.length < 6) { $inregisterPopupTypeGrip.error_password = true; $inregisterPopupTypeGrip.shake(); $inregisterPopupTypeGrip.validateRegister().passwordInputError(); return false; } }, passwordOk: function() { $("#register-password-v1").css('border', '2px solid green'); $inregisterPopupTypeGrip.validateRegister().passwordInputOk(); }, passwordInputOk: function() { $("#register-error-password-v1").removeClass("error"); $("#register-error-password-v1").css('opacity', 0); }, passwordError: function() { $("#register-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inregisterPopupTypeGrip.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); $("#register-error-password-v1").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputNullError: function() { $inregisterPopupTypeGrip.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); // $("#register-error-password-v1").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetFirstname: function() { $("#register-firstname-v1").css('border', ''); $("#register-firstname-v1").val(''); $("#register-error-firstname-v1").css('opacity', 0); }, resetLastname: function() { $("#register-lastname-v1").css('border', ''); $("#register-lastname-v1").val(''); $("#register-error-lastname-v1").css('opacity', 0); }, resetBandcode: function() { $("#register-bandcode-v1").css('border', ''); $("#register-bandcode-v1").val(''); $("#register-error-bandcode-v1").css('opacity', 0); }, resetAddress: function() { $("#register-address-v1").css('border', ''); $("#register-address-v1").val(''); $("#register-error-address-v1").css('opacity', 0); }, resetVehicle: function() { $("#register-vehicle-v1").css('border', ''); $("#register-vehicle-v1").val(''); $("#register-error-vehicle-v1").css('opacity', 0); }, resetProvince: function() { $("#register-province-v1").css('border', ''); $("#register-province-v1").val(0); $("#register-error-province-v1").css('opacity', 0); }, resetAmphoe: function() { $("#register-amphoe-v1").css('border', ''); $("#register-amphoe-v1").val(0); $("#register-error-amphoe-v1").css('opacity', 0); }, resetTambon: function() { $("#register-tambon-v1").css('border', ''); $("#register-tambon-v1").val(0); $("#register-error-tambon-v1").css('opacity', 0); }, resetPostel: function() { $("#register-postel-v1").css('border', ''); $("#register-postel-v1").val(''); $("#register-error-postel-v1").css('opacity', 0); }, resetEmail: function() { $("#register-email-v1").css('border', ''); $("#register-email-v1").val(''); $("#register-error-email-v1").css('opacity', 0); }, resetIdnumber: function() { $("#register-idnumber-v1").css('border', ''); $("#register-idnumber-v1").val(''); $("#register-error-idnumber-v1").css('opacity', 0); }, resetBobile: function() { $("#register-mobile-v1").css('border', ''); $("#register-mobile-v1").val(''); $("#register-error-mobile-v1").css('opacity', 0); }, resetPassword: function() { $("#register-password-v1").css('border', ''); $("#register-password-v1").val(''); $("#register-error-password-v1").css('opacity', 0); }, resetLocation: function(css_id) { $(css_id).html(''); }, reset: function() { $inregisterPopupTypeGrip.validateRegister().resetFirstname(); $inregisterPopupTypeGrip.validateRegister().resetLastname(); $inregisterPopupTypeGrip.validateRegister().resetBandcode(); $inregisterPopupTypeGrip.validateRegister().resetAddress(); $inregisterPopupTypeGrip.validateRegister().resetVehicle(); $inregisterPopupTypeGrip.validateRegister().resetProvince(); $inregisterPopupTypeGrip.validateRegister().resetAmphoe(); $inregisterPopupTypeGrip.validateRegister().resetTambon(); $inregisterPopupTypeGrip.validateRegister().resetPostel(); $inregisterPopupTypeGrip.validateRegister().resetEmail(); $inregisterPopupTypeGrip.validateRegister().resetIdnumber(); $inregisterPopupTypeGrip.validateRegister().resetBobile(); $inregisterPopupTypeGrip.validateRegister().resetPassword(); }, }; return promise; }; /* validateRegister */ /* load html */ $inregisterPopupTypeGrip.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inregisterPopupTypeGrip.whenOnLoad = function(shopId) {}; $inregisterPopupTypeGrip.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isFormat: function(format, data) { return format.test(data); }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isFirstname: function(firstname) { var re1 = /^[a-zA-Zก-๙]+$/; var re2 = /^[^๐-๙]+$/; var state = false; var firstname_re1 = re1.test(firstname); if (firstname_re1) { state = true; var firstname_re2 = re2.test(firstname); if (firstname_re2) { return state; } else { return false; } } else { return false; } }, isLastname: function(lastname) { var re1 = /^[a-zA-Zก-๙]+$/; var re2 = /^[^๐-๙]+$/; var state = false; var lastname_re1 = re1.test(lastname); if (lastname_re1) { state = true; var lastname_re2 = re2.test(lastname); if (lastname_re2) { return state; } else { return false; } } else { return false; } }, isBandcode: function(bandcode) { var re = /^((([a-zA-Z]{2})+[0-9]{10}))$/; var bandcode = re.test(bandcode); if (bandcode) { return true; } else { return false; } }, isAddress: function(address) { if (address.length) { return true; } else { return false; } }, isVehicle: function(vehicle) { if (vehicle.length) { return true; } else { return false; } }, isProvince: function(province) { if (province != '0') { return true; } else { return false; } }, isAmphoe: function(amphoe) { if (amphoe != '0') { return true; } else { return false; } }, isTambon: function(tambon) { if (tambon != '0') { return true; } else { return false; } }, isPostel: function(postel) { if (postel.length) { return true; } else { return false; } }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isIdnumber: function(idnumber) { var re = /^(([0-9]{13}))$/; var result = re.test(idnumber); if (result) { return true; } else { return false; } }, isMobile: function(mobile) { var re = /^(([0-9]{8,10}))$/; var result = re.test(mobile); if (result) { return true; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.register_vGrip_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.register_vGrip_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, registerDone: function() { var load = $('.register_vGrip_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vGrip_done .register_done.from_background").addClass("is_open"); }, 100); }, registerUnDone: function() { var load = $('.register_vGrip_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vGrip_done .register_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitRegister */ $inregisterPopupTypeGrip.submitRegister = function() { $inregisterPopupTypeGrip.register.firstname = $inregisterPopupTypeGrip.validateRegister().getVal('#register-firstname-v1'); $inregisterPopupTypeGrip.register.lastname = $inregisterPopupTypeGrip.validateRegister().getVal('#register-lastname-v1'); /* $inregisterPopupTypeGrip.register.bandcode = $inregisterPopupTypeGrip.validateRegister().getVal('#register-bandcode-v1'); */ /* $inregisterPopupTypeGrip.register.address = $inregisterPopupTypeGrip.validateRegister().getVal('#register-address-v1'); */ // $inregisterPopupTypeGrip.register.vehicle = $inregisterPopupTypeGrip.validateRegister().getVal('#register-vehicle-v1'); // $inregisterPopupTypeGrip.register.province = $inregisterPopupTypeGrip.validateRegister().getVal('#register-province-v1'); /* $inregisterPopupTypeGrip.register.amphoe = $inregisterPopupTypeGrip.validateRegister().getVal('#register-amphoe-v1'); $inregisterPopupTypeGrip.register.tambon = $inregisterPopupTypeGrip.validateRegister().getVal('#register-tambon-v1'); $inregisterPopupTypeGrip.register.postel = $inregisterPopupTypeGrip.validateRegister().getVal('#register-postel-v1');*/ $inregisterPopupTypeGrip.register.email = $inregisterPopupTypeGrip.validateRegister().getVal('#register-email-v1'); /* $inregisterPopupTypeGrip.register.idnumber = $inregisterPopupTypeGrip.validateRegister().getVal('#register-idnumber-v1'); */ $inregisterPopupTypeGrip.register.mobile = $inregisterPopupTypeGrip.validateRegister().getVal('#register-mobile-v1'); $inregisterPopupTypeGrip.register.password = $inregisterPopupTypeGrip.validateRegister().getVal('#register-password-v1'); var userFirstnameValid = $inregisterPopupTypeGrip.validateRegister().firstname(); var userLastnameValid = $inregisterPopupTypeGrip.validateRegister().lastname(); /* var userBandcodeValid = $inregisterPopupTypeGrip.validateRegister().bandcode(); */ /* var userAddressValid = $inregisterPopupTypeGrip.validateRegister().address(); */ // var userVehicleValid = $inregisterPopupTypeGrip.validateRegister().vehicle(); // var userProvinceValid = $inregisterPopupTypeGrip.validateRegister().province(); /* var userAmphoeValid = $inregisterPopupTypeGrip.validateRegister().amphoe(); var userTambonValid = $inregisterPopupTypeGrip.validateRegister().tambon(); var userPostelValid = $inregisterPopupTypeGrip.validateRegister().postel(); */ var userEmailValid = $inregisterPopupTypeGrip.validateRegister().email(); /* var userIdnumberValid = $inregisterPopupTypeGrip.validateRegister().idnumber(); */ var userMobileValid = $inregisterPopupTypeGrip.validateRegister().mobile(); var userPassValid = $inregisterPopupTypeGrip.validateRegister().password(); if (!userFirstnameValid || !userLastnameValid || !userEmailValid || !userMobileValid || !userPassValid) { console.log("submitRegister", "return"); $inregisterPopupTypeGrip.shake(); return; } $inregisterPopupTypeGrip.validateRegister().checkEmail($inregisterPopupTypeGrip.register.email, function(resultCheck) { console.log("submitRegister", resultCheck); if (resultCheck.ok == 0) { console.log('submitRegister true'); $inregisterPopupTypeGrip.validateRegister().emailInputRepeatedly(); $inregisterPopupTypeGrip.validateRegister().passwordInputRepeatedly(); } else { console.log('submitRegister false'); return $inregisterPopupTypeGrip.sendSubmitRegister(false); } }); }; /* submitRegister */ /* sendSubmitRegister */ $inregisterPopupTypeGrip.sendSubmitRegister = function(reCheck) { $inregisterPopupTypeGrip.register.pressing = true var userFirstname = $inregisterPopupTypeGrip.register.firstname; var userLastname = $inregisterPopupTypeGrip.register.lastname; /* var userBandcode = $inregisterPopupTypeGrip.register.bandcode; */ /* var userAddress = $inregisterPopupTypeGrip.register.address; */ // var userVehicle = $inregisterPopupTypeGrip.register.vehicle; // var userProvince = parseInt($inregisterPopupTypeGrip.register.province); /* var userAmphoe = parseInt($inregisterPopupTypeGrip.register.amphoe); var userTambon = parseInt($inregisterPopupTypeGrip.register.tambon); var userPostel = $inregisterPopupTypeGrip.register.postel; */ // $inregisterPopupTypeGrip.getLocationId(userProvince, function(dataLocationId) { // console.log("$inregisterPopupTypeGrip : sendSubmitRegister : userProvince : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); // userProvince = dataLocationId.location_name; var userEmail = $inregisterPopupTypeGrip.register.email; var userIdnumber = $inregisterPopupTypeGrip.register.idnumber; var userMobile = $inregisterPopupTypeGrip.register.mobile; var userPass = $inregisterPopupTypeGrip.register.password; console.log("sendSubmitRegister", reCheck); if (reCheck) { /* if error : firstname */ if (userFirstname.length <= 0) { $inregisterPopupTypeGrip.validateRegister().firstnameInputError(); } else { $inregisterPopupTypeGrip.validateRegister().firstnameOk(); } /* if error : lastname */ if (userLastname.length <= 0) { $inregisterPopupTypeGrip.validateRegister().lastnameInputError(); } else { $inregisterPopupTypeGrip.validateRegister().lastnameOk(); } /* if error : userBandcode */ /* if (userBandcode.length <= 0) { $inregisterPopupTypeGrip.validateRegister().bandcodeInputError(); } else { $inregisterPopupTypeGrip.validateRegister().bandcodeOk(); } */ /* if error : userAddress */ /* if (userAddress.length <= 0) { $inregisterPopupTypeGrip.validateRegister().addressInputError(); } else { $inregisterPopupTypeGrip.validateRegister().addressOk(); } */ /* if error : userVehicle */ // if (userVehicle.length <= 0) { // $inregisterPopupTypeGrip.validateRegister().vehicleInputError(); // } else { // $inregisterPopupTypeGrip.validateRegister().vehicleOk(); // } /* if error : userProvince */ // if (userProvince.length <= 0) { // $inregisterPopupTypeGrip.validateRegister().provinceInputError(); // } else { // $inregisterPopupTypeGrip.validateRegister().provinceOk(); // } /* if error : userAmphoe */ /* if (userAmphoe.length <= 0) { $inregisterPopupTypeGrip.validateRegister().amphoeInputError(); } else { $inregisterPopupTypeGrip.validateRegister().amphoeOk(); } */ /* if error : userTambon */ /* if (userTambon.length <= 0) { $inregisterPopupTypeGrip.validateRegister().tambonInputError(); } else { $inregisterPopupTypeGrip.validateRegister().tambonOk(); } */ /* if error : userPostel */ /* if (userPostel.length <= 0) { $inregisterPopupTypeGrip.validateRegister().postelInputError(); } else { $inregisterPopupTypeGrip.validateRegister().postelOk(); } */ /* if error : user */ if (userEmail.length <= 0) { $inregisterPopupTypeGrip.validateRegister().emailInputError(); } else { $inregisterPopupTypeGrip.validateRegister().emailOk(); } /* if error : userIdnumber */ /* if (userIdnumber.length <= 0) { $inregisterPopupTypeGrip.validateRegister().idnumberInputError(); } else { $inregisterPopupTypeGrip.validateRegister().idnumberOk(); } */ /* if error : userMobile */ if (userMobile.length <= 0) { $inregisterPopupTypeGrip.validateRegister().mobileInputError(); } else { $inregisterPopupTypeGrip.validateRegister().mobileOk(); } /* if error : pass */ if (userPass.length <= 0) { $inregisterPopupTypeGrip.validateRegister().passwordOk(); } else { $inregisterPopupTypeGrip.validateRegister().passwordInputError(); } /* firstname */ if (userFirstname.length > 0 && !$inregisterPopupTypeGrip.helper.isFirstname(userFirstname)) { $inregisterPopupTypeGrip.error_firstname = true; } else { $inregisterPopupTypeGrip.error_firstname = false; } /* lastname */ if (userLastname.length > 0 && !$inregisterPopupTypeGrip.helper.isLastname(userLastname)) { $inregisterPopupTypeGrip.error_lastname = true; } else { $inregisterPopupTypeGrip.error_lastname = false; } /* bandcode */ /* if (userBandcode.length > 0 && !$inregisterPopupTypeGrip.helper.isBandcode(userBandcode)) { $inregisterPopupTypeGrip.error_bandcode = true; } else { $inregisterPopupTypeGrip.error_bandcode = false; } */ /* email */ if (userEmail.length > 0 && !$inregisterPopupTypeGrip.helper.isEmail(userEmail)) { $inregisterPopupTypeGrip.error_email = true; } else { $inregisterPopupTypeGrip.error_email = false; } /* userIdnumber */ /* if (userIdnumber.length > 0 && !$inregisterPopupTypeGrip.helper.isIdnumber(userIdnumber)) { $inregisterPopupTypeGrip.error_idnumber = true; } else { $inregisterPopupTypeGrip.error_idnumber = false; } */ /* userMobile */ if (userMobile.length > 0 && !$inregisterPopupTypeGrip.helper.isMobile(userMobile)) { $inregisterPopupTypeGrip.error_mobile = true; } else { $inregisterPopupTypeGrip.error_mobile = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inregisterPopupTypeGrip.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inregisterPopupTypeGrip.error_password = true; } console.log("sendSubmitRegister : ", "error_firstname : ", $inregisterPopupTypeGrip.error_firstname, "error_lastname : ", $inregisterPopupTypeGrip.error_lastname, "error_email : ", $inregisterPopupTypeGrip.error_email, "error_password : ", $inregisterPopupTypeGrip.error_password); if ($inregisterPopupTypeGrip.error_firstname || $inregisterPopupTypeGrip.error_lastname || $inregisterPopupTypeGrip.error_bandcode || $inregisterPopupTypeGrip.error_email || $inregisterPopupTypeGrip.error_idnumber || $inregisterPopupTypeGrip.error_mobile || $inregisterPopupTypeGrip.error_password) { console.log("sendSubmitRegister return"); $inregisterPopupTypeGrip.shake(); return; } } /* loading */ $inregisterPopupTypeGrip.helper.pageLoad(); var dataSend = { 'txt_first_name': userFirstname, 'txt_last_name': userLastname, 'txt_email': userEmail, 'txt_phone': userMobile, 'txt_password': userPass }; console.log("sendSubmitRegister txt_email : ", dataSend); GAEAPI.post("ui/api/ui_customer_box/customer/register", dataSend).then(function(output) { console.log("sendSubmitRegister register : ", output); if (output.ok == 1) { $inregisterPopupTypeGrip.close(); $inregisterPopupTypeGrip.helper.pageUnLoad(); $inregisterPopupTypeGrip.helper.registerDone(); GAEAPI.get('customer/logout', {}).then(function(output_logout) { if (output_logout.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); } else { $inregisterPopupTypeGrip.helper.pageUnLoad(); alert("Register ผิดพลาด! กรุณาลองใหม่อีกครั้ง"); } }); // }); /* loading */ }; /* sendSubmitRegister */ /* viewPassword */ $inregisterPopupTypeGrip.viewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); if (t === 'password') { e.attr('type', 'text'); } else { e.attr('type', 'password'); } }; $inregisterPopupTypeGrip.resetViewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); e.attr('type', 'password'); }; /* viewPassword */ $inregisterPopupTypeGrip.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inregisterPopupTypeGrip.isOpen = false; $inregisterPopupTypeGrip.open = function() { $inregisterPopupTypeGrip.resetViewPassword('register-password-v1'); $inregisterPopupTypeGrip.validateRegister().reset(); $(".register_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'relative' }); timerAdjustOpen = setTimeout(function() { $(".register.from_background").addClass("is_open"); }, 100); $inregisterPopupTypeGrip.getLocation(2, 231, 1, 100, '', '', function(dataLocation) { console.log("$inregisterPopupTypeGrip : open : dataLocation : ", dataLocation); for (var i = 0; i < dataLocation.length; i++) { console.log("2 $inregisterPopupTypeGrip : open : for : dataLocation[" + i + "] : ", dataLocation[i]); $('#register-province-v1').append(''); } }); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inregisterPopupTypeGrip.submitRegister(); } }); }; /* Open */ /* Close */ $inregisterPopupTypeGrip.close = function() { $(".register_overlay").removeClass("is_open"); $(".register.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inregisterPopupTypeGrip.shake = function() { $(".register.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".register.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inregisterPopupTypeGrip.login = function() { $inregisterPopupTypeGrip.close(); $inregisterPopupTypeGrip.helper.registerUnDone(); $inloginPopup.open(); } /* login */ /* toHome */ $inregisterPopupTypeGrip.toHome = function() { $inregisterPopupTypeGrip.helper.registerUnDone(); window.location.href = 'home'; }; /* toHome *//* Cart displat at right side of page */ var $inregisterPopupTypeInfosat = {}; /* params */ $inregisterPopupTypeInfosat.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentRegisterTypeInfosat/"; $inregisterPopupTypeInfosat.templateRoot = 'root.php'; $inregisterPopupTypeInfosat.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inregisterPopupTypeInfosat.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inregisterPopupTypeInfosat.install = function(shopId, customBuild) { /* dont install in (checkout, register) */ this.templateRoot = 'root.php'; $.get($inregisterPopupTypeInfosat.path + 'componentRegisterTypeInfosat.css', function(response) { $('head').append(''); }); $.get($inregisterPopupTypeInfosat.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inregisterPopupTypeInfosat.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inregisterPopupTypeInfosat.api = GURL.base_api_url(); /* Install */ /* register model */ $inregisterPopupTypeInfosat.register = { firstname: '', lastname: '', bandcode: '', address: '', province: '0', amphoe: '0', tambon: '0', postel: '', email: '', company: '', mobile: '', password: '', pressing: false, errore_mail: false, errore_password: false, }; $inregisterPopupTypeInfosat.error = { firstnameExist: false, lastnameExist: false, bandcodeExist: false, addressExist: false, provinceExist: false, amphoeExist: false, tambonExist: false, postelExist: false, emailExist: false, companyExist: false, mobileExist: false, firstname: false, lastname: false, bandcode: false, address: false, province: false, amphoe: false, tambon: false, postel: false, email: false, company: false, mobile: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* register model */ /* API LOCATION */ $inregisterPopupTypeInfosat.getLocation = function(type, location_id, cur_page, per_page, txt_sortby, search, callback) { var dataLocation = []; var option = { 'search': search }; var dataSend = { 'txt_location_type_id': type, 'txt_parent_id': location_id, 'cur_page': cur_page, 'per_page': per_page, 'txt_sortby': txt_sortby, 'txt_filter_json': JSON.stringify(option) }; console.log("$inregisterPopupTypeInfosat : getLocation : dataSend : ", dataSend); GAEAPI.get('location/lists', dataSend).then(function(output) { var getLocationTime = setTimeout(function() { window.clearTimeout(getLocationTime); console.log("$inregisterPopupTypeInfosat : getLocation : output : ", output); if (output.ok == 1) { dataLocation = output.data.dataList; } callback(dataLocation); }, 100); }); }; $inregisterPopupTypeInfosat.getLocationId = function(location_id, callback) { var dataLocationId = []; var dataSend = { 'txt_location_id': location_id, }; console.log("$inregisterPopupTypeInfosat : getLocation : dataSend : ", dataSend); GAEAPI.get('location/id', dataSend).then(function(output) { var getLocationIdTime = setTimeout(function() { window.clearTimeout(getLocationIdTime); console.log("$inregisterPopupTypeInfosat : getLocation : output : ", output); if (output.ok == 1) { dataLocationId = output.data; } callback(dataLocationId); }, 100); }); }; $inregisterPopupTypeInfosat.getLocationListsId = function(type, select_value, select_value_post) { console.log("$inregisterPopupTypeInfosat : getLocationListsId : type : ", type); console.log("$inregisterPopupTypeInfosat : getLocationListsId : select_value : ", select_value); console.log("$inregisterPopupTypeInfosat : getLocationListsId : select_value_post : ", select_value_post); var province_id = parseInt($(select_value).val()); console.log("$inregisterPopupTypeInfosat : getLocationListsId : select_value : ", $(select_value).val()); console.log("$inregisterPopupTypeInfosat : getLocationListsId : province_id : ", province_id); if (province_id != 0) { $inregisterPopupTypeInfosat.getLocation(type, province_id, 1, 200, '', '', function(dataLocation) { for (var i = 0; i < dataLocation.length; i++) { console.log("$inregisterPopupTypeInfosat : getLocationListsId : for : dataLocation[" + i + "] : ", dataLocation[i]); $(select_value_post).append(''); } }); } if (type == 3) { var css_id = [{ css_in: '#register-amphoe-v1', value_in: '0', value_in_text: 'เลือก Amphoe', }, { css_in: '#register-tambon-v1', value_in: '0', value_in_text: 'เลือก Tambon', }, { css_in: '#register-postel-v1', value_in: '0', value_in_text: 'เลือก Postel', }]; for (var i = 0; i < css_id.length; i++) { console.log("$inregisterPopupTypeInfosat : getLocationListsId : for : css_id[" + i + "] : ", css_id[i]); $inregisterPopupTypeInfosat.validateRegister().resetLocation(css_id[i].css_in); $(css_id[i].css_in).append(''); } } else if (type == 4) { var css_id = [{ css_in: '#register-tambon-v1', value_in: '0', value_in_text: 'เลือก Tambon', }, { css_in: '#register-postel-v1', value_in: '0', value_in_text: 'เลือก Postel', }]; for (var i = 0; i < css_id.length; i++) { console.log("$inregisterPopupTypeInfosat : getLocationListsId : for : css_id[" + i + "] : ", css_id[i]); $inregisterPopupTypeInfosat.validateRegister().resetLocation(css_id[i].css_in); $(css_id[i].css_in).append(''); } } }; $inregisterPopupTypeInfosat.getLocationPostel = function(select_value) { console.log("$inregisterPopupTypeInfosat : getLocationPostel : select_value : ", select_value); var postel = parseInt($(select_value).val()); console.log("$inregisterPopupTypeInfosat : getLocationId : select_value : ", $(select_value).val()); console.log("$inregisterPopupTypeInfosat : getLocationId : postel : ", postel); if (postel != 0) { $inregisterPopupTypeInfosat.getLocationId(postel, function(dataLocationId) { console.log("$inregisterPopupTypeInfosat : getLocationId : dataLocationId.location_postcode : ", dataLocationId.location_postcode); $("#register-postel-v1").val(dataLocationId.location_postcode); }); } }; /* API LOCATION */ /* validateRegister */ $inregisterPopupTypeInfosat.validateRegister = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inregisterPopupTypeInfosat.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, getVal: function(cssID) { return $(cssID).val(); }, focusFirstname: function() { $inregisterPopupTypeInfosat.error.firstname = false; $inregisterPopupTypeInfosat.error.firstnameExist = false; $('#register-firstname-v1').css('border', ''); }, focusLastname: function() { $inregisterPopupTypeInfosat.error.lastname = false; $inregisterPopupTypeInfosat.error.lastnameExist = false; $('#register-lastname-v1').css('border', ''); }, focusBandcode: function() { $inregisterPopupTypeInfosat.error.bandcode = false; $inregisterPopupTypeInfosat.error.bandcodeExist = false; $('#register-bandcode-v1').css('border', ''); }, focusAddress: function() { $inregisterPopupTypeInfosat.error.address = false; $inregisterPopupTypeInfosat.error.addressExist = false; $('#register-address-v1').css('border', ''); }, focusProvince: function() { $inregisterPopupTypeInfosat.error.province = false; $inregisterPopupTypeInfosat.error.provinceExist = false; $('#register-province-v1').css('border', ''); }, focusAmphoe: function() { $inregisterPopupTypeInfosat.error.amphoe = false; $inregisterPopupTypeInfosat.error.amphoeExist = false; $('#register-amphoe-v1').css('border', ''); }, focusTambon: function() { $inregisterPopupTypeInfosat.error.tambon = false; $inregisterPopupTypeInfosat.error.tambonExist = false; $('#register-tambon-v1').css('border', ''); }, focusPostel: function() { $inregisterPopupTypeInfosat.error.postel = false; $inregisterPopupTypeInfosat.error.postelExist = false; $('#register-postel-v1').css('border', ''); }, focusEmail: function() { $inregisterPopupTypeInfosat.error.email = false; $inregisterPopupTypeInfosat.error.emailExist = false; $('#register-email-v1').css('border', ''); }, focusCompany: function() { $inregisterPopupTypeInfosat.error.company = false; $inregisterPopupTypeInfosat.error.companyExist = false; $('#register-company-v1').css('border', ''); }, focusBobile: function() { $inregisterPopupTypeInfosat.error.mobile = false; $inregisterPopupTypeInfosat.error.mobileExist = false; $('#register-mobile-v1').css('border', ''); }, focusPassword: function() { $inregisterPopupTypeInfosat.error_password = false; $inregisterPopupTypeInfosat.error.wrong_password = false; $('#register-password-v1').css('border', ''); }, firstname: function() { var v = $('#register-firstname-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isFirstname(v, true); console.log("firstname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().firstnameInputNullError(); $inregisterPopupTypeInfosat.error_firstname = false; $inregisterPopupTypeInfosat.error_firstnameExist = false; return false; } else { if (v.length > 0 && !valid) { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().firstnameInputError(); $inregisterPopupTypeInfosat.error_firstname = true; return false; } else if (v.length > 0 && valid) { $inregisterPopupTypeInfosat.validateRegister().firstnameOk(); return true; } } }, lastname: function() { var v = $('#register-lastname-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isLastname(v, true); console.log("lastname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().lastnameInputNullError(); $inregisterPopupTypeInfosat.error_lastname = false; $inregisterPopupTypeInfosat.error_lastnameExist = false; return false; } else { if (v.length > 0 && valid) { $inregisterPopupTypeInfosat.validateRegister().lastnameOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().lastnameInputError(); $inregisterPopupTypeInfosat.error_lastname = true; return false; } } }, bandcode: function() { var v = $('#register-bandcode-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isBandcode(v); console.log("inregisterPopupTypeInfosat : bandcode : v : ", v); console.log("inregisterPopupTypeInfosat : bandcode : valid : ", valid); if (valid) { $inregisterPopupTypeInfosat.validateRegister().bandcodeOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().bandcodeInputNullError(); return false; } }, address: function() { var v = $('#register-address-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isAddress(v); console.log("inregisterPopupTypeInfosat : address : v : ", v); console.log("inregisterPopupTypeInfosat : address : valid : ", valid); if (valid) { $inregisterPopupTypeInfosat.validateRegister().addressOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().addressInputNullError(); return false; } }, province: function() { var v = $('#register-province-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isProvince(v); console.log("inregisterPopupTypeInfosat : province : v : ", v); console.log("inregisterPopupTypeInfosat : province : valid : ", valid); if (valid) { $inregisterPopupTypeInfosat.validateRegister().provinceOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().provinceInputNullError(); return false; } }, amphoe: function() { var v = $('#register-amphoe-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isAmphoe(v); console.log("inregisterPopupTypeInfosat : amphoe : v : ", v); console.log("inregisterPopupTypeInfosat : amphoe : valid : ", valid); if (valid) { $inregisterPopupTypeInfosat.validateRegister().amphoeOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().amphoeInputNullError(); return false; } }, tambon: function() { var v = $('#register-tambon-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isTambon(v); console.log("inregisterPopupTypeInfosat : tambon : v : ", v); console.log("inregisterPopupTypeInfosat : tambon : valid : ", valid); if (valid) { $inregisterPopupTypeInfosat.validateRegister().tambonOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().tambonInputNullError(); return false; } }, postel: function() { var v = $('#register-postel-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isAddress(v); console.log("inregisterPopupTypeInfosat : postel : v : ", v); console.log("inregisterPopupTypeInfosat : postel : valid : ", valid); if (valid) { $inregisterPopupTypeInfosat.validateRegister().postelOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().postelInputNullError(); return false; } }, email: function() { var v = $('#register-email-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isEmail(v); console.log("inregisterPopupTypeInfosat : email : v : ", v); console.log("inregisterPopupTypeInfosat : email : valid : ", valid); if (valid) { $inregisterPopupTypeInfosat.validateRegister().emailOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().emailInputNullError(); return false; } }, company: function() { var v = $('#register-company-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isCompany(v); console.log("inregisterPopupTypeInfosat : company : v : ", v); console.log("inregisterPopupTypeInfosat : company : valid : ", valid); if (valid) { $inregisterPopupTypeInfosat.validateRegister().companyOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().companyInputNullError(); return false; } }, mobile: function() { var v = $('#register-mobile-v1').val(); var t = this; var valid = $inregisterPopupTypeInfosat.helper.isMobile(v); console.log("inregisterPopupTypeInfosat : mobile : v : ", v); console.log("inregisterPopupTypeInfosat : mobile : valid : ", valid); if (valid) { $inregisterPopupTypeInfosat.validateRegister().mobileOk(); return true; } else { $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().mobileInputNullError(); return false; } }, firstnameOk: function() { $('#register-firstname-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().firstnameInputOk(); }, lastnameOk: function() { $('#register-lastname-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().lastnameInputOk(); }, bandcodeOk: function() { $('#register-bandcode-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().bandcodeInputOk(); }, addressOk: function() { $('#register-address-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().addressInputOk(); }, provinceOk: function() { $('#register-province-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().provinceInputOk(); }, amphoeOk: function() { $('#register-amphoe-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().amphoeInputOk(); }, tambonOk: function() { $('#register-tambon-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().tambonInputOk(); }, postelOk: function() { $('#register-postel-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().postelInputOk(); }, emailOk: function() { $('#register-email-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().emailInputOk(); }, companyOk: function() { $('#register-company-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().companyInputOk(); }, mobileOk: function() { $('#register-mobile-v1').css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().mobileInputOk(); }, firstnameInputOk: function() { $("#register-error-firstname-v1").removeClass("error"); $("#register-error-firstname-v1").css('opacity', 0); }, lastnameInputOk: function() { $("#register-error-lastname-v1").removeClass("error"); $("#register-error-lastname-v1").css('opacity', 0); }, bandcodeInputOk: function() { $("#register-error-bandcode-v1").removeClass("error"); $("#register-error-bandcode-v1").css('opacity', 0); }, addressInputOk: function() { $("#register-error-address-v1").removeClass("error"); $("#register-error-address-v1").css('opacity', 0); }, provinceInputOk: function() { $("#register-error-province-v1").removeClass("error"); $("#register-error-province-v1").css('opacity', 0); }, amphoeInputOk: function() { $("#register-error-amphoe-v1").removeClass("error"); $("#register-error-amphoe-v1").css('opacity', 0); }, tambonInputOk: function() { $("#register-error-tambon-v1").removeClass("error"); $("#register-error-tambon-v1").css('opacity', 0); }, postelInputOk: function() { $("#register-error-postel-v1").removeClass("error"); $("#register-error-postel-v1").css('opacity', 0); }, emailInputOk: function() { $("#register-error-email-v1").removeClass("error"); $("#register-error-email-v1").css('opacity', 0); }, companyInputOk: function() { $("#register-error-company-v1").removeClass("error"); $("#register-error-company-v1").css('opacity', 0); }, mobileInputOk: function() { $("#register-error-mobile-v1").removeClass("error"); $("#register-error-mobile-v1").css('opacity', 0); }, firstnameError: function() { $("#register-firstname-v1").css('border', '2px solid red'); }, lastnameError: function() { $("#register-lastname-v1").css('border', '2px solid red'); }, bandcodeError: function() { $("#register-bandcode-v1").css('border', '2px solid red'); }, addressError: function() { $("#register-address-v1").css('border', '2px solid red'); }, provinceError: function() { $("#register-province-v1").css('border', '2px solid red'); }, amphoeError: function() { $("#register-amphoe-v1").css('border', '2px solid red'); }, tambonError: function() { $("#register-tambon-v1").css('border', '2px solid red'); }, postelError: function() { $("#register-postel-v1").css('border', '2px solid red'); }, emailError: function() { $("#register-email-v1").css('border', '2px solid red'); }, companyError: function() { $("#register-company-v1").css('border', '2px solid red'); }, mobileError: function() { $("#register-mobile-v1").css('border', '2px solid red'); }, firstnameInputError: function() { $inregisterPopupTypeInfosat.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputError: function() { $inregisterPopupTypeInfosat.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, bandcodeInputError: function() { $inregisterPopupTypeInfosat.validateRegister().lastnameError(); $("#register-error-bandcode-v1").addClass("error"); $("#register-error-bandcode-v1").css('opacity', 1).html('กรุณาใส่รหัสกลุ่มแบนด์ที่เคยเดินทาง'); }, addressInputError: function() { $inregisterPopupTypeInfosat.validateRegister().addressError(); $("#register-error-address-v1").addClass("error"); $("#register-error-address-v1").css('opacity', 1).html('กรุณาใส่ที่อยู่'); }, provinceInputError: function() { $inregisterPopupTypeInfosat.validateRegister().addressError(); $("#register-error-province-v1").addClass("error"); $("#register-error-province-v1").css('opacity', 1).html('กรุณาเลือกจังหวัด'); }, amphoeInputError: function() { $inregisterPopupTypeInfosat.validateRegister().addressError(); $("#register-error-amphoe-v1").addClass("error"); $("#register-error-amphoe-v1").css('opacity', 1).html('กรุณาเลือกอำเภอ'); }, tambonInputError: function() { $inregisterPopupTypeInfosat.validateRegister().addressError(); $("#register-error-tambon-v1").addClass("error"); $("#register-error-tambon-v1").css('opacity', 1).html('กรุณาเลือกตำบล'); }, postelInputError: function() { $inregisterPopupTypeInfosat.validateRegister().postelError(); $("#register-error-postel-v1").addClass("error"); $("#register-error-postel-v1").css('opacity', 1).html('กรุณาใส่รหัสไปรษณีย์'); }, emailInputRepeatedly: function() { $inregisterPopupTypeInfosat.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('อีเมลนี้มีการลงทะเบียนเป็นสมาชิกแล้ว Email already exists'); }, companyInputError: function() { $inregisterPopupTypeInfosat.validateRegister().lastnameError(); $("#register-error-company-v1").addClass("error"); $("#register-error-company-v1").css('opacity', 1).html('กรุณาใส่ ชื่อร้าน / บริษัท'); }, mobileInputError: function() { $inregisterPopupTypeInfosat.validateRegister().lastnameError(); $("#register-error-mobile-v1").addClass("error"); $("#register-error-mobile-v1").css('opacity', 1).html('กรุณาใส่เบอร์โทรศัพท์'); }, passwordInputRepeatedly: function() { $("#register-password-v1").css('border', '1px solid #dddddd'); }, emailInputError: function() { $inregisterPopupTypeInfosat.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, firstnameInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); // $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); // $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, bandcodeInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().bandcodeError(); $("#register-error-bandcode-v1").addClass("error"); // $("#register-error-bandcode-v1").css('opacity', 1).html('กรุณาใส่รหัสรหัสกลุ่มแบนด์ที่เคยเดินทาง'); }, addressInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().addressError(); $("#register-error-address-v1").addClass("error"); // $("#register-error-address-v1").css('opacity', 1).html('กรุณาใส่ที่อยู่ '); }, provinceInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().provinceError(); $("#register-error-province-v1").addClass("error"); // $("#register-error-province-v1").css('opacity', 1).html('กรุณาเลือกจังหวัด'); }, amphoeInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().amphoeError(); $("#register-error-amphoe-v1").addClass("error"); // $("#register-error-amphoe-v1").css('opacity', 1).html('กรุณาเลือกอำเภอ'); }, tambonInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().tambonError(); $("#register-error-tambon-v1").addClass("error"); // $("#register-error-tambon-v1").css('opacity', 1).html('กรุณาเลือกตำบล'); }, postelInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().postelError(); $("#register-error-postel-v1").addClass("error"); // $("#register-error-postel-v1").css('opacity', 1).html('กรุณาใส่รหัสไปรษณีย์ '); }, emailInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); // $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, companyInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().companyError(); $("#register-error-company-v1").addClass("error"); // $("#register-error-company-v1").css('opacity', 1).html('กรุณาใส่ ชื่อร้าน / บริษัท'); }, mobileInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().mobileError(); $("#register-error-mobile-v1").addClass("error"); // $("#register-error-mobile-v1").css('opacity', 1).html('กรุณาใส่เบอร์โทรศัพท์'); }, password: function() { var v = $('#register-password-v1').val(); if (v.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().passwordInputNullError(); $inregisterPopupTypeInfosat.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inregisterPopupTypeInfosat.error_password = false; $inregisterPopupTypeInfosat.validateRegister().passwordOk(); return true; } else if (v.length > 0 && v.length < 6) { $inregisterPopupTypeInfosat.error_password = true; $inregisterPopupTypeInfosat.shake(); $inregisterPopupTypeInfosat.validateRegister().passwordInputError(); return false; } }, passwordOk: function() { $("#register-password-v1").css('border', '2px solid green'); $inregisterPopupTypeInfosat.validateRegister().passwordInputOk(); }, passwordInputOk: function() { $("#register-error-password-v1").removeClass("error"); $("#register-error-password-v1").css('opacity', 0); }, passwordError: function() { $("#register-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inregisterPopupTypeInfosat.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); $("#register-error-password-v1").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputNullError: function() { $inregisterPopupTypeInfosat.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); // $("#register-error-password-v1").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetFirstname: function() { $("#register-firstname-v1").css('border', ''); $("#register-firstname-v1").val(''); $("#register-error-firstname-v1").css('opacity', 0); }, resetLastname: function() { $("#register-lastname-v1").css('border', ''); $("#register-lastname-v1").val(''); $("#register-error-lastname-v1").css('opacity', 0); }, resetBandcode: function() { $("#register-bandcode-v1").css('border', ''); $("#register-bandcode-v1").val(''); $("#register-error-bandcode-v1").css('opacity', 0); }, resetAddress: function() { $("#register-address-v1").css('border', ''); $("#register-address-v1").val(''); $("#register-error-address-v1").css('opacity', 0); }, resetProvince: function() { $("#register-province-v1").css('border', ''); $("#register-province-v1").val(0); $("#register-error-province-v1").css('opacity', 0); }, resetAmphoe: function() { $("#register-amphoe-v1").css('border', ''); $("#register-amphoe-v1").val(0); $("#register-error-amphoe-v1").css('opacity', 0); }, resetTambon: function() { $("#register-tambon-v1").css('border', ''); $("#register-tambon-v1").val(0); $("#register-error-tambon-v1").css('opacity', 0); }, resetPostel: function() { $("#register-postel-v1").css('border', ''); $("#register-postel-v1").val(''); $("#register-error-postel-v1").css('opacity', 0); }, resetEmail: function() { $("#register-email-v1").css('border', ''); $("#register-email-v1").val(''); $("#register-error-email-v1").css('opacity', 0); }, resetCompany: function() { $("#register-company-v1").css('border', ''); $("#register-company-v1").val(''); $("#register-error-company-v1").css('opacity', 0); }, resetBobile: function() { $("#register-mobile-v1").css('border', ''); $("#register-mobile-v1").val(''); $("#register-error-mobile-v1").css('opacity', 0); }, resetPassword: function() { $("#register-password-v1").css('border', ''); $("#register-password-v1").val(''); $("#register-error-password-v1").css('opacity', 0); }, resetLocation: function(css_id) { $(css_id).html(''); }, reset: function() { $inregisterPopupTypeInfosat.validateRegister().resetFirstname(); $inregisterPopupTypeInfosat.validateRegister().resetLastname(); $inregisterPopupTypeInfosat.validateRegister().resetBandcode(); $inregisterPopupTypeInfosat.validateRegister().resetAddress(); $inregisterPopupTypeInfosat.validateRegister().resetProvince(); $inregisterPopupTypeInfosat.validateRegister().resetAmphoe(); $inregisterPopupTypeInfosat.validateRegister().resetTambon(); $inregisterPopupTypeInfosat.validateRegister().resetPostel(); $inregisterPopupTypeInfosat.validateRegister().resetEmail(); $inregisterPopupTypeInfosat.validateRegister().resetCompany(); $inregisterPopupTypeInfosat.validateRegister().resetBobile(); $inregisterPopupTypeInfosat.validateRegister().resetPassword(); }, }; return promise; }; /* validateRegister */ /* load html */ $inregisterPopupTypeInfosat.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inregisterPopupTypeInfosat.whenOnLoad = function(shopId) {}; $inregisterPopupTypeInfosat.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isFormat: function(format, data) { return format.test(data); }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isFirstname: function(firstname) { if (firstname.length > 1) { return true; } else { return false; } }, isLastname: function(lastname) { if (lastname.length > 1) { return true; } else { return false; } }, isBandcode: function(bandcode) { var re = /^((([a-zA-Z]{2})+[0-9]{10}))$/; var bandcode = re.test(bandcode); if (bandcode) { return true; } else { return false; } }, isAddress: function(address) { if (address.length) { return true; } else { return false; } }, isProvince: function(province) { if (province != '0') { return true; } else { return false; } }, isAmphoe: function(amphoe) { if (amphoe != '0') { return true; } else { return false; } }, isTambon: function(tambon) { if (tambon != '0') { return true; } else { return false; } }, isPostel: function(postel) { if (postel.length) { return true; } else { return false; } }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isCompany: function(company) { if (company.length) { return true; } else { return false; } }, isMobile: function(mobile) { var re = /^(([0-9]{8,10}))$/; var result = re.test(mobile); if (result) { return true; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.register_vInfosat_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.register_vInfosat_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, registerDone: function() { var load = $('.register_vInfosat_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vInfosat_done .register_done.from_background").addClass("is_open"); }, 100); }, registerUnDone: function() { var load = $('.register_vInfosat_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vInfosat_done .register_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitRegister */ $inregisterPopupTypeInfosat.submitRegister = function() { $inregisterPopupTypeInfosat.register.firstname = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-firstname-v1'); $inregisterPopupTypeInfosat.register.lastname = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-lastname-v1'); $inregisterPopupTypeInfosat.register.company = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-company-v1'); $inregisterPopupTypeInfosat.register.address = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-address-v1'); $inregisterPopupTypeInfosat.register.province = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-province-v1'); $inregisterPopupTypeInfosat.register.amphoe = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-amphoe-v1'); $inregisterPopupTypeInfosat.register.tambon = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-tambon-v1'); $inregisterPopupTypeInfosat.register.postel = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-postel-v1'); $inregisterPopupTypeInfosat.register.email = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-email-v1'); $inregisterPopupTypeInfosat.register.mobile = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-mobile-v1'); $inregisterPopupTypeInfosat.register.password = $inregisterPopupTypeInfosat.validateRegister().getVal('#register-password-v1'); var userFirstnameValid = $inregisterPopupTypeInfosat.validateRegister().firstname(); var userLastnameValid = $inregisterPopupTypeInfosat.validateRegister().lastname(); var userCompanyValid = $inregisterPopupTypeInfosat.validateRegister().company(); var userAddressValid = $inregisterPopupTypeInfosat.validateRegister().address(); var userProvinceValid = $inregisterPopupTypeInfosat.validateRegister().province(); var userAmphoeValid = $inregisterPopupTypeInfosat.validateRegister().amphoe(); var userTambonValid = $inregisterPopupTypeInfosat.validateRegister().tambon(); var userPostelValid = $inregisterPopupTypeInfosat.validateRegister().postel(); var userEmailValid = $inregisterPopupTypeInfosat.validateRegister().email(); var userMobileValid = $inregisterPopupTypeInfosat.validateRegister().mobile(); var userPassValid = $inregisterPopupTypeInfosat.validateRegister().password(); if (!userFirstnameValid || !userLastnameValid || !userCompanyValid || !userAddressValid || !userProvinceValid || !userAmphoeValid || !userTambonValid || !userPostelValid || !userEmailValid || !userMobileValid || !userPassValid) { console.log("submitRegister", "return"); $inregisterPopupTypeInfosat.shake(); return; } $inregisterPopupTypeInfosat.validateRegister().checkEmail($inregisterPopupTypeInfosat.register.email, function(resultCheck) { console.log("submitRegister", resultCheck); if (resultCheck.ok == 0) { console.log('submitRegister true'); $inregisterPopupTypeInfosat.validateRegister().emailInputRepeatedly(); $inregisterPopupTypeInfosat.validateRegister().passwordInputRepeatedly(); } else { console.log('submitRegister false'); return $inregisterPopupTypeInfosat.sendSubmitRegister(false); } }); }; /* submitRegister */ /* sendSubmitRegister */ $inregisterPopupTypeInfosat.sendSubmitRegister = function(reCheck) { $inregisterPopupTypeInfosat.register.pressing = true var userFirstname = $inregisterPopupTypeInfosat.register.firstname; var userLastname = $inregisterPopupTypeInfosat.register.lastname; var userCompany = $inregisterPopupTypeInfosat.register.company; var userAddress = $inregisterPopupTypeInfosat.register.address; var userProvince = parseInt($inregisterPopupTypeInfosat.register.province); var userAmphoe = parseInt($inregisterPopupTypeInfosat.register.amphoe); var userTambon = parseInt($inregisterPopupTypeInfosat.register.tambon); var userPostel = $inregisterPopupTypeInfosat.register.postel; $inregisterPopupTypeInfosat.getLocationId(userProvince, function(dataLocationId) { console.log("$inregisterPopupTypeInfosat : sendSubmitRegister : userProvince : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); userProvince = dataLocationId.location_name; $inregisterPopupTypeInfosat.getLocationId(userAmphoe, function(dataLocationId) { console.log("$inregisterPopupTypeInfosat : sendSubmitRegister : userAmphoe : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); userAmphoe = dataLocationId.location_name; $inregisterPopupTypeInfosat.getLocationId(userTambon, function(dataLocationId) { console.log("$inregisterPopupTypeInfosat : sendSubmitRegister : userTambon : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); userTambon = dataLocationId.location_name; var userEmail = $inregisterPopupTypeInfosat.register.email; var userMobile = $inregisterPopupTypeInfosat.register.mobile; var userPass = $inregisterPopupTypeInfosat.register.password; console.log("sendSubmitRegister", reCheck); if (reCheck) { /* if error : firstname */ if (userFirstname.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().firstnameInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().firstnameOk(); } /* if error : lastname */ if (userLastname.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().lastnameInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().lastnameOk(); } /* if error : company */ if (userCompany.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().companyInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().companyOk(); } /* if error : userAddress */ if (userAddress.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().addressInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().addressOk(); } /* if error : userProvince */ if (userProvince.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().provinceInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().provinceOk(); } /* if error : userAmphoe */ if (userAmphoe.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().amphoeInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().amphoeOk(); } /* if error : userTambon */ if (userTambon.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().tambonInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().tambonOk(); } /* if error : userPostel */ if (userPostel.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().postelInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().postelOk(); } /* if error : user */ if (userEmail.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().emailInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().emailOk(); } /* if error : userMobile */ if (userMobile.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().mobileInputError(); } else { $inregisterPopupTypeInfosat.validateRegister().mobileOk(); } /* if error : pass */ if (userPass.length <= 0) { $inregisterPopupTypeInfosat.validateRegister().passwordOk(); } else { $inregisterPopupTypeInfosat.validateRegister().passwordInputError(); } /* firstname */ if (userFirstname.length > 0 && !$inregisterPopupTypeInfosat.helper.isFirstname(userFirstname)) { $inregisterPopupTypeInfosat.error_firstname = true; } else { $inregisterPopupTypeInfosat.error_firstname = false; } /* lastname */ if (userLastname.length > 0 && !$inregisterPopupTypeInfosat.helper.isLastname(userLastname)) { $inregisterPopupTypeInfosat.error_lastname = true; } else { $inregisterPopupTypeInfosat.error_lastname = false; } /* company */ if (userCompany.length > 0 && !$inregisterPopupTypeInfosat.helper.isCompany(userCompany)) { $inregisterPopupTypeInfosat.error_company = true; } else { $inregisterPopupTypeInfosat.error_company = false; } /* email */ if (userEmail.length > 0 && !$inregisterPopupTypeInfosat.helper.isEmail(userEmail)) { $inregisterPopupTypeInfosat.error_email = true; } else { $inregisterPopupTypeInfosat.error_email = false; } /* userMobile */ if (userMobile.length > 0 && !$inregisterPopupTypeInfosat.helper.isMobile(userMobile)) { $inregisterPopupTypeInfosat.error_mobile = true; } else { $inregisterPopupTypeInfosat.error_mobile = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inregisterPopupTypeInfosat.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inregisterPopupTypeInfosat.error_password = true; } console.log("sendSubmitRegister : ", "error_firstname : ", $inregisterPopupTypeInfosat.error_firstname, "error_lastname : ", $inregisterPopupTypeInfosat.error_lastname, "error_email : ", $inregisterPopupTypeInfosat.error_email, "error_password : ", $inregisterPopupTypeInfosat.error_password); if ($inregisterPopupTypeInfosat.error_firstname || $inregisterPopupTypeInfosat.error_lastname || $inregisterPopupTypeInfosat.error_company || $inregisterPopupTypeInfosat.error_bandcode || $inregisterPopupTypeInfosat.error_email || $inregisterPopupTypeInfosat.error_company || $inregisterPopupTypeInfosat.error_mobile || $inregisterPopupTypeInfosat.error_password) { console.log("sendSubmitRegister return"); $inregisterPopupTypeInfosat.shake(); return; } } /* loading */ $inregisterPopupTypeInfosat.helper.pageLoad(); var dataSend = { 'txt_first_name': userFirstname, 'txt_last_name': userLastname, 'txt_info_address': userAddress, 'txt_info_province': userProvince, 'txt_info_amphoe': userAmphoe, 'txt_info_tambon': userTambon, 'txt_info_postcode': userPostel, 'txt_email': userEmail, 'txt_note': userCompany, 'txt_phone': userMobile, 'txt_password': userPass }; console.log("sendSubmitRegister txt_email : ", dataSend); GAEAPI.post("ui/api/ui_customer_box/customer/register", dataSend).then(function(output) { console.log("sendSubmitRegister register : ", output); if (output.ok == 1) { $inregisterPopupTypeInfosat.close(); $inregisterPopupTypeInfosat.helper.pageUnLoad(); $inregisterPopupTypeInfosat.helper.registerDone(); GAEAPI.get('customer/logout', {}).then(function(output_logout) { if (output_logout.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); } else { $inregisterPopupTypeInfosat.helper.pageUnLoad(); alert("Register ผิดพลาด! กรุณาลองใหม่อีกครั้ง"); } }); }); }); }); /* loading */ }; /* sendSubmitRegister */ /* viewPassword */ $inregisterPopupTypeInfosat.viewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); if (t === 'password') { e.attr('type', 'text'); } else { e.attr('type', 'password'); } }; $inregisterPopupTypeInfosat.resetViewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); e.attr('type', 'password'); }; /* viewPassword */ $inregisterPopupTypeInfosat.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inregisterPopupTypeInfosat.isOpen = false; $inregisterPopupTypeInfosat.open = function() { $inregisterPopupTypeInfosat.resetViewPassword('register-password-v1'); $inregisterPopupTypeInfosat.validateRegister().reset(); $(".register_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'hidden', 'position': 'fixed' }); timerAdjustOpen = setTimeout(function() { $(".register.from_background").addClass("is_open"); }, 100); $inregisterPopupTypeInfosat.getLocation(2, 231, 1, 100, '', '', function(dataLocation) { console.log("$inregisterPopupTypeInfosat : open : dataLocation : ", dataLocation); for (var i = 0; i < dataLocation.length; i++) { console.log("2 $inregisterPopupTypeInfosat : open : for : dataLocation[" + i + "] : ", dataLocation[i]); $('#register-province-v1').append(''); } }); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inregisterPopupTypeInfosat.submitRegister(); } }); }; /* Open */ /* Close */ $inregisterPopupTypeInfosat.close = function() { $(".register_overlay").removeClass("is_open"); $(".register.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inregisterPopupTypeInfosat.shake = function() { $(".register.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".register.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inregisterPopupTypeInfosat.login = function() { $inregisterPopupTypeInfosat.close(); $inregisterPopupTypeInfosat.helper.registerUnDone(); $inloginPopup.open(); } /* login */ /* toHome */ $inregisterPopupTypeInfosat.toHome = function() { $inregisterPopupTypeInfosat.helper.registerUnDone(); window.location.href = 'home'; }; /* toHome *//* Cart displat at right side of page */ var $inregisterPopupTypeSirikhu = {}; /* params */ $inregisterPopupTypeSirikhu.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentRegisterTypeSirikhun/"; $inregisterPopupTypeSirikhu.templateRoot = 'root.php'; $inregisterPopupTypeSirikhu.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $inregisterPopupTypeSirikhu.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $inregisterPopupTypeSirikhu.install = function(shopId, customBuild) { /* dont install in (checkout, register) */ this.templateRoot = 'root.php'; $.get($inregisterPopupTypeSirikhu.path + 'componentRegisterTypeSirikhun.css', function(response) { $('head').append(''); }); $.get($inregisterPopupTypeSirikhu.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $inregisterPopupTypeSirikhu.path }, function(response) { $('body').append(response); }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); }, 2000); }; $inregisterPopupTypeSirikhu.api = GURL.base_api_url(); /* Install */ /* register model */ $inregisterPopupTypeSirikhu.register = { firstname: '', lastname: '', bandcode: '', address: '', province: '0', amphoe: '0', tambon: '0', postel: '', email: '', company: '', mobile: '', password: '', pressing: false, errore_mail: false, errore_password: false, }; $inregisterPopupTypeSirikhu.error = { firstnameExist: false, lastnameExist: false, bandcodeExist: false, addressExist: false, provinceExist: false, amphoeExist: false, tambonExist: false, postelExist: false, emailExist: false, companyExist: false, mobileExist: false, firstname: false, lastname: false, bandcode: false, address: false, province: false, amphoe: false, tambon: false, postel: false, email: false, company: false, mobile: false, emailText: 'ตรวจสอบรูปแบบอีเมล Email should be valid (name@domain.com)', password: false, passwordText: ' ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format', wrong_password: false, }; /* register model */ /* API LOCATION */ $inregisterPopupTypeSirikhu.getLocation = function(type, location_id, cur_page, per_page, txt_sortby, search, callback) { var dataLocation = []; var option = { 'search': search }; var dataSend = { 'txt_location_type_id': type, 'txt_parent_id': location_id, 'cur_page': cur_page, 'per_page': per_page, 'txt_sortby': txt_sortby, 'txt_filter_json': JSON.stringify(option) }; console.log("$inregisterPopupTypeSirikhu : getLocation : dataSend : ", dataSend); GAEAPI.get('location/lists', dataSend).then(function(output) { var getLocationTime = setTimeout(function() { window.clearTimeout(getLocationTime); console.log("$inregisterPopupTypeSirikhu : getLocation : output : ", output); if (output.ok == 1) { dataLocation = output.data.dataList; } callback(dataLocation); }, 100); }); }; $inregisterPopupTypeSirikhu.getLocationId = function(location_id, callback) { var dataLocationId = []; var dataSend = { 'txt_location_id': location_id, }; console.log("$inregisterPopupTypeSirikhu : getLocation : dataSend : ", dataSend); GAEAPI.get('location/id', dataSend).then(function(output) { var getLocationIdTime = setTimeout(function() { window.clearTimeout(getLocationIdTime); console.log("$inregisterPopupTypeSirikhu : getLocation : output : ", output); if (output.ok == 1) { dataLocationId = output.data; } callback(dataLocationId); }, 100); }); }; $inregisterPopupTypeSirikhu.getLocationListsId = function(type, select_value, select_value_post) { console.log("$inregisterPopupTypeSirikhu : getLocationListsId : type : ", type); console.log("$inregisterPopupTypeSirikhu : getLocationListsId : select_value : ", select_value); console.log("$inregisterPopupTypeSirikhu : getLocationListsId : select_value_post : ", select_value_post); var province_id = parseInt($(select_value).val()); console.log("$inregisterPopupTypeSirikhu : getLocationListsId : select_value : ", $(select_value).val()); console.log("$inregisterPopupTypeSirikhu : getLocationListsId : province_id : ", province_id); if (province_id != 0) { $inregisterPopupTypeSirikhu.getLocation(type, province_id, 1, 200, '', '', function(dataLocation) { for (var i = 0; i < dataLocation.length; i++) { console.log("$inregisterPopupTypeSirikhu : getLocationListsId : for : dataLocation[" + i + "] : ", dataLocation[i]); $(select_value_post).append(''); } }); } if (type == 3) { var css_id = [{ css_in: '#register-amphoe-v1', value_in: '0', value_in_text: 'เลือก Amphoe', }, { css_in: '#register-tambon-v1', value_in: '0', value_in_text: 'เลือก Tambon', }, { css_in: '#register-postel-v1', value_in: '0', value_in_text: 'เลือก Postel', }]; for (var i = 0; i < css_id.length; i++) { console.log("$inregisterPopupTypeSirikhu : getLocationListsId : for : css_id[" + i + "] : ", css_id[i]); $inregisterPopupTypeSirikhu.validateRegister().resetLocation(css_id[i].css_in); $(css_id[i].css_in).append(''); } } else if (type == 4) { var css_id = [{ css_in: '#register-tambon-v1', value_in: '0', value_in_text: 'เลือก Tambon', }, { css_in: '#register-postel-v1', value_in: '0', value_in_text: 'เลือก Postel', }]; for (var i = 0; i < css_id.length; i++) { console.log("$inregisterPopupTypeSirikhu : getLocationListsId : for : css_id[" + i + "] : ", css_id[i]); $inregisterPopupTypeSirikhu.validateRegister().resetLocation(css_id[i].css_in); $(css_id[i].css_in).append(''); } } }; $inregisterPopupTypeSirikhu.getLocationPostel = function(select_value) { console.log("$inregisterPopupTypeSirikhu : getLocationPostel : select_value : ", select_value); var postel = parseInt($(select_value).val()); console.log("$inregisterPopupTypeSirikhu : getLocationId : select_value : ", $(select_value).val()); console.log("$inregisterPopupTypeSirikhu : getLocationId : postel : ", postel); if (postel != 0) { $inregisterPopupTypeSirikhu.getLocationId(postel, function(dataLocationId) { console.log("$inregisterPopupTypeSirikhu : getLocationId : dataLocationId.location_postcode : ", dataLocationId.location_postcode); $("#register-postel-v1").val(dataLocationId.location_postcode); }); } }; /* API LOCATION */ /* validateRegister */ $inregisterPopupTypeSirikhu.validateRegister = function() { var promise = { checkEmail: function(v, callback) { $.ajax({ type: 'POST', method: 'POST', url: $inregisterPopupTypeSirikhu.host() + 'customer/is_exists_email', data: { txt_email: v }, datatType: 'json' }).done(function(e) { callback(e); }); }, getVal: function(cssID) { return $(cssID).val(); }, focusFirstname: function() { $inregisterPopupTypeSirikhu.error.firstname = false; $inregisterPopupTypeSirikhu.error.firstnameExist = false; $('#register-firstname-v1').css('border', ''); }, focusLastname: function() { $inregisterPopupTypeSirikhu.error.lastname = false; $inregisterPopupTypeSirikhu.error.lastnameExist = false; $('#register-lastname-v1').css('border', ''); }, focusBandcode: function() { $inregisterPopupTypeSirikhu.error.bandcode = false; $inregisterPopupTypeSirikhu.error.bandcodeExist = false; $('#register-bandcode-v1').css('border', ''); }, focusAddress: function() { $inregisterPopupTypeSirikhu.error.address = false; $inregisterPopupTypeSirikhu.error.addressExist = false; $('#register-address-v1').css('border', ''); }, focusProvince: function() { $inregisterPopupTypeSirikhu.error.province = false; $inregisterPopupTypeSirikhu.error.provinceExist = false; $('#register-province-v1').css('border', ''); }, focusAmphoe: function() { $inregisterPopupTypeSirikhu.error.amphoe = false; $inregisterPopupTypeSirikhu.error.amphoeExist = false; $('#register-amphoe-v1').css('border', ''); }, focusTambon: function() { $inregisterPopupTypeSirikhu.error.tambon = false; $inregisterPopupTypeSirikhu.error.tambonExist = false; $('#register-tambon-v1').css('border', ''); }, focusPostel: function() { $inregisterPopupTypeSirikhu.error.postel = false; $inregisterPopupTypeSirikhu.error.postelExist = false; $('#register-postel-v1').css('border', ''); }, focusEmail: function() { $inregisterPopupTypeSirikhu.error.email = false; $inregisterPopupTypeSirikhu.error.emailExist = false; $('#register-email-v1').css('border', ''); }, focusCompany: function() { $inregisterPopupTypeSirikhu.error.company = false; $inregisterPopupTypeSirikhu.error.companyExist = false; $('#register-company-v1').css('border', ''); }, focusBobile: function() { $inregisterPopupTypeSirikhu.error.mobile = false; $inregisterPopupTypeSirikhu.error.mobileExist = false; $('#register-mobile-v1').css('border', ''); }, focusPassword: function() { $inregisterPopupTypeSirikhu.error_password = false; $inregisterPopupTypeSirikhu.error.wrong_password = false; $('#register-password-v1').css('border', ''); }, firstname: function() { var v = $('#register-firstname-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isFirstname(v, true); console.log("firstname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().firstnameInputNullError(); $inregisterPopupTypeSirikhu.error_firstname = false; $inregisterPopupTypeSirikhu.error_firstnameExist = false; return false; } else { if (v.length > 0 && !valid) { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().firstnameInputError(); $inregisterPopupTypeSirikhu.error_firstname = true; return false; } else if (v.length > 0 && valid) { $inregisterPopupTypeSirikhu.validateRegister().firstnameOk(); return true; } } }, lastname: function() { var v = $('#register-lastname-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isLastname(v, true); console.log("lastname v.length : ", v.length, " valid : ", valid); if (v.length <= 0) { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().lastnameInputNullError(); $inregisterPopupTypeSirikhu.error_lastname = false; $inregisterPopupTypeSirikhu.error_lastnameExist = false; return false; } else { if (v.length > 0 && valid) { $inregisterPopupTypeSirikhu.validateRegister().lastnameOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().lastnameInputError(); $inregisterPopupTypeSirikhu.error_lastname = true; return false; } } }, bandcode: function() { var v = $('#register-bandcode-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isBandcode(v); console.log("inregisterPopupTypeSirikhu : bandcode : v : ", v); console.log("inregisterPopupTypeSirikhu : bandcode : valid : ", valid); if (valid) { $inregisterPopupTypeSirikhu.validateRegister().bandcodeOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().bandcodeInputNullError(); return false; } }, address: function() { var v = $('#register-address-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isAddress(v); console.log("inregisterPopupTypeSirikhu : address : v : ", v); console.log("inregisterPopupTypeSirikhu : address : valid : ", valid); if (valid) { $inregisterPopupTypeSirikhu.validateRegister().addressOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().addressInputNullError(); return false; } }, province: function() { var v = $('#register-province-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isProvince(v); console.log("inregisterPopupTypeSirikhu : province : v : ", v); console.log("inregisterPopupTypeSirikhu : province : valid : ", valid); if (valid) { $inregisterPopupTypeSirikhu.validateRegister().provinceOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().provinceInputNullError(); return false; } }, amphoe: function() { var v = $('#register-amphoe-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isAmphoe(v); console.log("inregisterPopupTypeSirikhu : amphoe : v : ", v); console.log("inregisterPopupTypeSirikhu : amphoe : valid : ", valid); if (valid) { $inregisterPopupTypeSirikhu.validateRegister().amphoeOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().amphoeInputNullError(); return false; } }, tambon: function() { var v = $('#register-tambon-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isTambon(v); console.log("inregisterPopupTypeSirikhu : tambon : v : ", v); console.log("inregisterPopupTypeSirikhu : tambon : valid : ", valid); if (valid) { $inregisterPopupTypeSirikhu.validateRegister().tambonOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().tambonInputNullError(); return false; } }, postel: function() { var v = $('#register-postel-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isAddress(v); console.log("inregisterPopupTypeSirikhu : postel : v : ", v); console.log("inregisterPopupTypeSirikhu : postel : valid : ", valid); if (valid) { $inregisterPopupTypeSirikhu.validateRegister().postelOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().postelInputNullError(); return false; } }, email: function() { var v = $('#register-email-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isEmail(v); console.log("inregisterPopupTypeSirikhu : email : v : ", v); console.log("inregisterPopupTypeSirikhu : email : valid : ", valid); if (valid) { $inregisterPopupTypeSirikhu.validateRegister().emailOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().emailInputNullError(); return false; } }, company: function() { var v = $('#register-company-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isCompany(v); console.log("inregisterPopupTypeSirikhu : company : v : ", v); console.log("inregisterPopupTypeSirikhu : company : valid : ", valid); if (valid) { $inregisterPopupTypeSirikhu.validateRegister().companyOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().companyInputNullError(); return false; } }, mobile: function() { var v = $('#register-mobile-v1').val(); var t = this; var valid = $inregisterPopupTypeSirikhu.helper.isMobile(v); console.log("inregisterPopupTypeSirikhu : mobile : v : ", v); console.log("inregisterPopupTypeSirikhu : mobile : valid : ", valid); if (valid) { $inregisterPopupTypeSirikhu.validateRegister().mobileOk(); return true; } else { $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().mobileInputNullError(); return false; } }, firstnameOk: function() { $('#register-firstname-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().firstnameInputOk(); }, lastnameOk: function() { $('#register-lastname-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().lastnameInputOk(); }, bandcodeOk: function() { $('#register-bandcode-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().bandcodeInputOk(); }, addressOk: function() { $('#register-address-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().addressInputOk(); }, provinceOk: function() { $('#register-province-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().provinceInputOk(); }, amphoeOk: function() { $('#register-amphoe-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().amphoeInputOk(); }, tambonOk: function() { $('#register-tambon-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().tambonInputOk(); }, postelOk: function() { $('#register-postel-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().postelInputOk(); }, emailOk: function() { $('#register-email-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().emailInputOk(); }, companyOk: function() { $('#register-company-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().companyInputOk(); }, mobileOk: function() { $('#register-mobile-v1').css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().mobileInputOk(); }, firstnameInputOk: function() { $("#register-error-firstname-v1").removeClass("error"); $("#register-error-firstname-v1").css('opacity', 0); }, lastnameInputOk: function() { $("#register-error-lastname-v1").removeClass("error"); $("#register-error-lastname-v1").css('opacity', 0); }, bandcodeInputOk: function() { $("#register-error-bandcode-v1").removeClass("error"); $("#register-error-bandcode-v1").css('opacity', 0); }, addressInputOk: function() { $("#register-error-address-v1").removeClass("error"); $("#register-error-address-v1").css('opacity', 0); }, provinceInputOk: function() { $("#register-error-province-v1").removeClass("error"); $("#register-error-province-v1").css('opacity', 0); }, amphoeInputOk: function() { $("#register-error-amphoe-v1").removeClass("error"); $("#register-error-amphoe-v1").css('opacity', 0); }, tambonInputOk: function() { $("#register-error-tambon-v1").removeClass("error"); $("#register-error-tambon-v1").css('opacity', 0); }, postelInputOk: function() { $("#register-error-postel-v1").removeClass("error"); $("#register-error-postel-v1").css('opacity', 0); }, emailInputOk: function() { $("#register-error-email-v1").removeClass("error"); $("#register-error-email-v1").css('opacity', 0); }, companyInputOk: function() { $("#register-error-company-v1").removeClass("error"); $("#register-error-company-v1").css('opacity', 0); }, mobileInputOk: function() { $("#register-error-mobile-v1").removeClass("error"); $("#register-error-mobile-v1").css('opacity', 0); }, firstnameError: function() { $("#register-firstname-v1").css('border', '2px solid red'); }, lastnameError: function() { $("#register-lastname-v1").css('border', '2px solid red'); }, bandcodeError: function() { $("#register-bandcode-v1").css('border', '2px solid red'); }, addressError: function() { $("#register-address-v1").css('border', '2px solid red'); }, provinceError: function() { $("#register-province-v1").css('border', '2px solid red'); }, amphoeError: function() { $("#register-amphoe-v1").css('border', '2px solid red'); }, tambonError: function() { $("#register-tambon-v1").css('border', '2px solid red'); }, postelError: function() { $("#register-postel-v1").css('border', '2px solid red'); }, emailError: function() { $("#register-email-v1").css('border', '2px solid red'); }, companyError: function() { $("#register-company-v1").css('border', '2px solid red'); }, mobileError: function() { $("#register-mobile-v1").css('border', '2px solid red'); }, firstnameInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, bandcodeInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().lastnameError(); $("#register-error-bandcode-v1").addClass("error"); $("#register-error-bandcode-v1").css('opacity', 1).html('กรุณาใส่รหัสกลุ่มแบนด์ที่เคยเดินทาง'); }, addressInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().addressError(); $("#register-error-address-v1").addClass("error"); $("#register-error-address-v1").css('opacity', 1).html('กรุณาใส่ที่อยู่'); }, provinceInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().addressError(); $("#register-error-province-v1").addClass("error"); $("#register-error-province-v1").css('opacity', 1).html('กรุณาเลือกจังหวัด'); }, amphoeInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().addressError(); $("#register-error-amphoe-v1").addClass("error"); $("#register-error-amphoe-v1").css('opacity', 1).html('กรุณาเลือกอำเภอ'); }, tambonInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().addressError(); $("#register-error-tambon-v1").addClass("error"); $("#register-error-tambon-v1").css('opacity', 1).html('กรุณาเลือกตำบล'); }, postelInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().postelError(); $("#register-error-postel-v1").addClass("error"); $("#register-error-postel-v1").css('opacity', 1).html('กรุณาใส่รหัสไปรษณีย์'); }, emailInputRepeatedly: function() { $inregisterPopupTypeSirikhu.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('อีเมลนี้มีการลงทะเบียนเป็นสมาชิกแล้ว Email already exists'); }, companyInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().lastnameError(); $("#register-error-company-v1").addClass("error"); $("#register-error-company-v1").css('opacity', 1).html('กรุณาใส่ ชื่อร้าน / บริษัท'); }, mobileInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().lastnameError(); $("#register-error-mobile-v1").addClass("error"); $("#register-error-mobile-v1").css('opacity', 1).html('กรุณาใส่เบอร์โทรศัพท์'); }, passwordInputRepeatedly: function() { $("#register-password-v1").css('border', '1px solid #dddddd'); }, emailInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid เช่น getappeasy@gmail.com'); }, firstnameInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().firstnameError(); $("#register-error-firstname-v1").addClass("error"); // $("#register-error-firstname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบชื่อ Please check your format'); }, lastnameInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().lastnameError(); $("#register-error-lastname-v1").addClass("error"); // $("#register-error-lastname-v1").css('opacity', 1).html('ตรวจสอบรูปแบบนามสกุล Please check your format'); }, bandcodeInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().bandcodeError(); $("#register-error-bandcode-v1").addClass("error"); // $("#register-error-bandcode-v1").css('opacity', 1).html('กรุณาใส่รหัสรหัสกลุ่มแบนด์ที่เคยเดินทาง'); }, addressInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().addressError(); $("#register-error-address-v1").addClass("error"); // $("#register-error-address-v1").css('opacity', 1).html('กรุณาใส่ที่อยู่ '); }, provinceInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().provinceError(); $("#register-error-province-v1").addClass("error"); // $("#register-error-province-v1").css('opacity', 1).html('กรุณาเลือกจังหวัด'); }, amphoeInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().amphoeError(); $("#register-error-amphoe-v1").addClass("error"); // $("#register-error-amphoe-v1").css('opacity', 1).html('กรุณาเลือกอำเภอ'); }, tambonInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().tambonError(); $("#register-error-tambon-v1").addClass("error"); // $("#register-error-tambon-v1").css('opacity', 1).html('กรุณาเลือกตำบล'); }, postelInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().postelError(); $("#register-error-postel-v1").addClass("error"); // $("#register-error-postel-v1").css('opacity', 1).html('กรุณาใส่รหัสไปรษณีย์ '); }, emailInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().emailError(); $("#register-error-email-v1").addClass("error"); // $("#register-error-email-v1").css('opacity', 1).html('ตรวจสอบรูปแบบอีเมล ​Email should be valid (name@domain.com)'); }, companyInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().companyError(); $("#register-error-company-v1").addClass("error"); // $("#register-error-company-v1").css('opacity', 1).html('กรุณาใส่ ชื่อร้าน / บริษัท'); }, mobileInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().mobileError(); $("#register-error-mobile-v1").addClass("error"); // $("#register-error-mobile-v1").css('opacity', 1).html('กรุณาใส่เบอร์โทรศัพท์'); }, password: function() { var v = $('#register-password-v1').val(); if (v.length <= 0) { $inregisterPopupTypeSirikhu.validateRegister().passwordInputNullError(); $inregisterPopupTypeSirikhu.shake(); return false; } if (v.length > 0 && v.length >= 6) { $inregisterPopupTypeSirikhu.error_password = false; $inregisterPopupTypeSirikhu.validateRegister().passwordOk(); return true; } else if (v.length > 0 && v.length < 6) { $inregisterPopupTypeSirikhu.error_password = true; $inregisterPopupTypeSirikhu.shake(); $inregisterPopupTypeSirikhu.validateRegister().passwordInputError(); return false; } }, passwordOk: function() { $("#register-password-v1").css('border', '2px solid green'); $inregisterPopupTypeSirikhu.validateRegister().passwordInputOk(); }, passwordInputOk: function() { $("#register-error-password-v1").removeClass("error"); $("#register-error-password-v1").css('opacity', 0); }, passwordError: function() { $("#register-password-v1").css('border', '2px solid red'); }, passwordInputError: function() { $inregisterPopupTypeSirikhu.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); $("#register-error-password-v1").css('opacity', 1).html('ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, passwordInputNullError: function() { $inregisterPopupTypeSirikhu.validateRegister().passwordError(); $("#register-error-password-v1").addClass("error"); // $("#register-error-password-v1").css('opacity', 1).html('error password ตรวจสอบรูปแบบให้ถูกต้อง Please correct the format'); }, resetFirstname: function() { $("#register-firstname-v1").css('border', ''); $("#register-firstname-v1").val(''); $("#register-error-firstname-v1").css('opacity', 0); }, resetLastname: function() { $("#register-lastname-v1").css('border', ''); $("#register-lastname-v1").val(''); $("#register-error-lastname-v1").css('opacity', 0); }, resetBandcode: function() { $("#register-bandcode-v1").css('border', ''); $("#register-bandcode-v1").val(''); $("#register-error-bandcode-v1").css('opacity', 0); }, resetAddress: function() { $("#register-address-v1").css('border', ''); $("#register-address-v1").val(''); $("#register-error-address-v1").css('opacity', 0); }, resetProvince: function() { $("#register-province-v1").css('border', ''); $("#register-province-v1").val(0); $("#register-error-province-v1").css('opacity', 0); }, resetAmphoe: function() { $("#register-amphoe-v1").css('border', ''); $("#register-amphoe-v1").val(0); $("#register-error-amphoe-v1").css('opacity', 0); }, resetTambon: function() { $("#register-tambon-v1").css('border', ''); $("#register-tambon-v1").val(0); $("#register-error-tambon-v1").css('opacity', 0); }, resetPostel: function() { $("#register-postel-v1").css('border', ''); $("#register-postel-v1").val(''); $("#register-error-postel-v1").css('opacity', 0); }, resetEmail: function() { $("#register-email-v1").css('border', ''); $("#register-email-v1").val(''); $("#register-error-email-v1").css('opacity', 0); }, resetCompany: function() { $("#register-company-v1").css('border', ''); $("#register-company-v1").val(''); $("#register-error-company-v1").css('opacity', 0); }, resetBobile: function() { $("#register-mobile-v1").css('border', ''); $("#register-mobile-v1").val(''); $("#register-error-mobile-v1").css('opacity', 0); }, resetPassword: function() { $("#register-password-v1").css('border', ''); $("#register-password-v1").val(''); $("#register-error-password-v1").css('opacity', 0); }, resetLocation: function(css_id) { $(css_id).html(''); }, reset: function() { $inregisterPopupTypeSirikhu.validateRegister().resetFirstname(); $inregisterPopupTypeSirikhu.validateRegister().resetLastname(); $inregisterPopupTypeSirikhu.validateRegister().resetBandcode(); $inregisterPopupTypeSirikhu.validateRegister().resetAddress(); $inregisterPopupTypeSirikhu.validateRegister().resetProvince(); $inregisterPopupTypeSirikhu.validateRegister().resetAmphoe(); $inregisterPopupTypeSirikhu.validateRegister().resetTambon(); $inregisterPopupTypeSirikhu.validateRegister().resetPostel(); $inregisterPopupTypeSirikhu.validateRegister().resetEmail(); $inregisterPopupTypeSirikhu.validateRegister().resetCompany(); $inregisterPopupTypeSirikhu.validateRegister().resetBobile(); $inregisterPopupTypeSirikhu.validateRegister().resetPassword(); }, }; return promise; }; /* validateRegister */ /* load html */ $inregisterPopupTypeSirikhu.viewHtml = function(viewName) { var html = path + viewName; return html; }; $inregisterPopupTypeSirikhu.whenOnLoad = function(shopId) {}; $inregisterPopupTypeSirikhu.helper = { countDots: function(s1, letter) { return (s1.match(RegExp(letter, 'g')) || []).length; }, isFormat: function(format, data) { return format.test(data); }, isAlpabet: function(str) { var strObj = str.match(/^[a-zA-zก-๙]+/g); var returnStr = ""; for (var idx in strObj) { returnStr += strObj[idx].replace("^", ""); } return returnStr; }, isFirstname: function(firstname) { if (firstname.length > 1) { return true; } else { return false; } }, isLastname: function(lastname) { if (lastname.length > 1) { return true; } else { return false; } }, isBandcode: function(bandcode) { var re = /^((([a-zA-Z]{2})+[0-9]{10}))$/; var bandcode = re.test(bandcode); if (bandcode) { return true; } else { return false; } }, isAddress: function(address) { if (address.length) { return true; } else { return false; } }, isProvince: function(province) { if (province != '0') { return true; } else { return false; } }, isAmphoe: function(amphoe) { if (amphoe != '0') { return true; } else { return false; } }, isTambon: function(tambon) { if (tambon != '0') { return true; } else { return false; } }, isPostel: function(postel) { if (postel.length) { return true; } else { return false; } }, isEmail: function(email) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(email); var a = email.split('@'); var checkTopLevel = false; if (result && a.length > 1) { return (a[1].length >= 5) ? true : false; } else { return false; } }, isCompany: function(company) { if (company.length) { return true; } else { return false; } }, isMobile: function(mobile) { var re = /^(([0-9]{8,10}))$/; var result = re.test(mobile); if (result) { return true; } else { return false; } }, isChar: function(e) { var k = (e.which) ? e.which : e.keyCode; if (k >= 48 && k <= 57) { return false; } else { return k; } }, pageLoadState: false, pageLoad: function() { var load = $('.register_vSirikhu_load'); if (!load.hasClass('active')) { load.addClass('active'); } }, pageUnLoad: function() { var load = $('.register_vSirikhu_load'); if (load.hasClass('active')) { load.removeClass('active'); } }, registerDone: function() { var load = $('.register_vSirikhu_done'); if (!load.hasClass('active')) { load.addClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vSirikhu_done .register_done.from_background").addClass("is_open"); }, 100); }, registerUnDone: function() { var load = $('.register_vSirikhu_done'); if (load.hasClass('active')) { load.removeClass('active'); } timerAdjustOpen = setTimeout(function() { $(".register_vSirikhu_done .register_done.from_background").removeClass("is_open"); }, 100); }, }; /* load html */ /* submitRegister */ $inregisterPopupTypeSirikhu.submitRegister = function() { $inregisterPopupTypeSirikhu.register.firstname = $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-firstname-v1'); $inregisterPopupTypeSirikhu.register.lastname = $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-lastname-v1'); $inregisterPopupTypeSirikhu.register.company = ""; /* $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-company-v1'); */ $inregisterPopupTypeSirikhu.register.address = ""; /* $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-address-v1'); */ $inregisterPopupTypeSirikhu.register.province = ""; /* $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-province-v1'); */ $inregisterPopupTypeSirikhu.register.amphoe = ""; /* $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-amphoe-v1'); */ $inregisterPopupTypeSirikhu.register.tambon = ""; /* $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-tambon-v1'); */ $inregisterPopupTypeSirikhu.register.postel = ""; /* $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-postel-v1');*/ $inregisterPopupTypeSirikhu.register.email = $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-email-v1'); $inregisterPopupTypeSirikhu.register.mobile = $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-mobile-v1'); $inregisterPopupTypeSirikhu.register.password = $inregisterPopupTypeSirikhu.validateRegister().getVal('#register-password-v1'); var userFirstnameValid = $inregisterPopupTypeSirikhu.validateRegister().firstname(); var userLastnameValid = $inregisterPopupTypeSirikhu.validateRegister().lastname(); /* var userCompanyValid = $inregisterPopupTypeSirikhu.validateRegister().company(); var userAddressValid = $inregisterPopupTypeSirikhu.validateRegister().address(); var userProvinceValid = $inregisterPopupTypeSirikhu.validateRegister().province(); var userAmphoeValid = $inregisterPopupTypeSirikhu.validateRegister().amphoe(); var userTambonValid = $inregisterPopupTypeSirikhu.validateRegister().tambon(); var userPostelValid = $inregisterPopupTypeSirikhu.validateRegister().postel();*/ var userEmailValid = $inregisterPopupTypeSirikhu.validateRegister().email(); var userMobileValid = $inregisterPopupTypeSirikhu.validateRegister().mobile(); var userPassValid = $inregisterPopupTypeSirikhu.validateRegister().password(); if (!userFirstnameValid || !userLastnameValid || !userEmailValid || !userMobileValid || !userPassValid) { console.log("submitRegister", "return"); $inregisterPopupTypeSirikhu.shake(); return; } $inregisterPopupTypeSirikhu.validateRegister().checkEmail($inregisterPopupTypeSirikhu.register.email, function(resultCheck) { console.log("submitRegister", resultCheck); if (resultCheck.ok == 0) { console.log('submitRegister true'); $inregisterPopupTypeSirikhu.validateRegister().emailInputRepeatedly(); $inregisterPopupTypeSirikhu.validateRegister().passwordInputRepeatedly(); } else { console.log('submitRegister false'); return $inregisterPopupTypeSirikhu.sendSubmitRegister(false); } }); }; /* submitRegister */ /* sendSubmitRegister */ $inregisterPopupTypeSirikhu.sendSubmitRegister = function(reCheck) { $inregisterPopupTypeSirikhu.register.pressing = true var userFirstname = $inregisterPopupTypeSirikhu.register.firstname; var userLastname = $inregisterPopupTypeSirikhu.register.lastname; var userCompany = $inregisterPopupTypeSirikhu.register.company; var userAddress = $inregisterPopupTypeSirikhu.register.address; var userProvince = parseInt($inregisterPopupTypeSirikhu.register.province); var userAmphoe = parseInt($inregisterPopupTypeSirikhu.register.amphoe); var userTambon = parseInt($inregisterPopupTypeSirikhu.register.tambon); var userPostel = $inregisterPopupTypeSirikhu.register.postel; $inregisterPopupTypeSirikhu.getLocationId(userProvince, function(dataLocationId) { console.log("$inregisterPopupTypeSirikhu : sendSubmitRegister : userProvince : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); userProvince = dataLocationId.location_name; $inregisterPopupTypeSirikhu.getLocationId(userAmphoe, function(dataLocationId) { console.log("$inregisterPopupTypeSirikhu : sendSubmitRegister : userAmphoe : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); userAmphoe = dataLocationId.location_name; $inregisterPopupTypeSirikhu.getLocationId(userTambon, function(dataLocationId) { console.log("$inregisterPopupTypeSirikhu : sendSubmitRegister : userTambon : getLocationId : dataLocationId.location_name : ", dataLocationId.location_name); userTambon = dataLocationId.location_name; var userEmail = $inregisterPopupTypeSirikhu.register.email; var userMobile = $inregisterPopupTypeSirikhu.register.mobile; var userPass = $inregisterPopupTypeSirikhu.register.password; console.log("sendSubmitRegister", reCheck); if (reCheck) { /* if error : firstname */ if (userFirstname.length <= 0) { $inregisterPopupTypeSirikhu.validateRegister().firstnameInputError(); } else { $inregisterPopupTypeSirikhu.validateRegister().firstnameOk(); } /* if error : lastname */ if (userLastname.length <= 0) { $inregisterPopupTypeSirikhu.validateRegister().lastnameInputError(); } else { $inregisterPopupTypeSirikhu.validateRegister().lastnameOk(); } /* if error : company */ // if (userCompany.length <= 0) { // $inregisterPopupTypeSirikhu.validateRegister().companyInputError(); // } else { // $inregisterPopupTypeSirikhu.validateRegister().companyOk(); // } /* if error : userAddress */ // if (userAddress.length <= 0) { // $inregisterPopupTypeSirikhu.validateRegister().addressInputError(); // } else { // $inregisterPopupTypeSirikhu.validateRegister().addressOk(); // } /* if error : userProvince */ // if (userProvince.length <= 0) { // $inregisterPopupTypeSirikhu.validateRegister().provinceInputError(); // } else { // $inregisterPopupTypeSirikhu.validateRegister().provinceOk(); // } /* if error : userAmphoe */ // if (userAmphoe.length <= 0) { // $inregisterPopupTypeSirikhu.validateRegister().amphoeInputError(); // } else { // $inregisterPopupTypeSirikhu.validateRegister().amphoeOk(); // } /* if error : userTambon */ // if (userTambon.length <= 0) { // $inregisterPopupTypeSirikhu.validateRegister().tambonInputError(); // } else { // $inregisterPopupTypeSirikhu.validateRegister().tambonOk(); // } /* if error : userPostel */ // if (userPostel.length <= 0) { // $inregisterPopupTypeSirikhu.validateRegister().postelInputError(); // } else { // $inregisterPopupTypeSirikhu.validateRegister().postelOk(); // } /* if error : user */ if (userEmail.length <= 0) { $inregisterPopupTypeSirikhu.validateRegister().emailInputError(); } else { $inregisterPopupTypeSirikhu.validateRegister().emailOk(); } /* if error : userMobile */ if (userMobile.length <= 0) { $inregisterPopupTypeSirikhu.validateRegister().mobileInputError(); } else { $inregisterPopupTypeSirikhu.validateRegister().mobileOk(); } /* if error : pass */ if (userPass.length <= 0) { $inregisterPopupTypeSirikhu.validateRegister().passwordOk(); } else { $inregisterPopupTypeSirikhu.validateRegister().passwordInputError(); } /* firstname */ if (userFirstname.length > 0 && !$inregisterPopupTypeSirikhu.helper.isFirstname(userFirstname)) { $inregisterPopupTypeSirikhu.error_firstname = true; } else { $inregisterPopupTypeSirikhu.error_firstname = false; } /* lastname */ if (userLastname.length > 0 && !$inregisterPopupTypeSirikhu.helper.isLastname(userLastname)) { $inregisterPopupTypeSirikhu.error_lastname = true; } else { $inregisterPopupTypeSirikhu.error_lastname = false; } /* company */ // if (userCompany.length > 0 && !$inregisterPopupTypeSirikhu.helper.isCompany(userCompany)) { // $inregisterPopupTypeSirikhu.error_company = true; // } else { // $inregisterPopupTypeSirikhu.error_company = false; // } /* email */ if (userEmail.length > 0 && !$inregisterPopupTypeSirikhu.helper.isEmail(userEmail)) { $inregisterPopupTypeSirikhu.error_email = true; } else { $inregisterPopupTypeSirikhu.error_email = false; } /* userMobile */ if (userMobile.length > 0 && !$inregisterPopupTypeSirikhu.helper.isMobile(userMobile)) { $inregisterPopupTypeSirikhu.error_mobile = true; } else { $inregisterPopupTypeSirikhu.error_mobile = false; } /* password */ if (userPass.length > 0 && userPass.length >= 6) { $inregisterPopupTypeSirikhu.error_password = false; } else if (userPass.length > 0 && userPass.length < 6) { $inregisterPopupTypeSirikhu.error_password = true; } console.log("sendSubmitRegister : ", "error_firstname : ", $inregisterPopupTypeSirikhu.error_firstname, "error_lastname : ", $inregisterPopupTypeSirikhu.error_lastname, "error_email : ", $inregisterPopupTypeSirikhu.error_email, "error_password : ", $inregisterPopupTypeSirikhu.error_password); if ($inregisterPopupTypeSirikhu.error_firstname || $inregisterPopupTypeSirikhu.error_lastname || $inregisterPopupTypeSirikhu.error_company || $inregisterPopupTypeSirikhu.error_bandcode || $inregisterPopupTypeSirikhu.error_email || $inregisterPopupTypeSirikhu.error_company || $inregisterPopupTypeSirikhu.error_mobile || $inregisterPopupTypeSirikhu.error_password) { console.log("sendSubmitRegister return"); $inregisterPopupTypeSirikhu.shake(); return; } } /* loading */ $inregisterPopupTypeSirikhu.helper.pageLoad(); var dataSend = { 'txt_first_name': userFirstname, 'txt_last_name': userLastname, 'txt_info_address': userAddress, 'txt_info_province': userProvince, 'txt_info_amphoe': userAmphoe, 'txt_info_tambon': userTambon, 'txt_info_postcode': userPostel, 'txt_email': userEmail, 'txt_note': userLastname, 'txt_phone': userMobile, 'txt_password': userPass }; console.log("sendSubmitRegister txt_email : ", dataSend); GAEAPI.post("ui/api/ui_customer_box/customer/register", dataSend).then(function(output) { console.log("sendSubmitRegister register : ", output); if (output.ok == 1) { $inregisterPopupTypeSirikhu.close(); $inregisterPopupTypeSirikhu.helper.pageUnLoad(); $inregisterPopupTypeSirikhu.helper.registerDone(); GAEAPI.get('customer/logout', {}).then(function(output_logout) { if (output_logout.ok == 1) { UiCustomerBox.apiGetCustomerData(function() {}); } }); } else { $inregisterPopupTypeSirikhu.helper.pageUnLoad(); alert("Register ผิดพลาด! กรุณาลองใหม่อีกครั้ง"); } }); }); }); }); /* loading */ }; /* sendSubmitRegister */ /* viewPassword */ $inregisterPopupTypeSirikhu.viewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); if (t === 'password') { e.attr('type', 'text'); } else { e.attr('type', 'password'); } }; $inregisterPopupTypeSirikhu.resetViewPassword = function(elementId) { var e = $("#" + elementId); var t = e.attr('type'); e.attr('type', 'password'); }; /* viewPassword */ $inregisterPopupTypeSirikhu.host = function() { if (window.location.href.indexOf('localhost') !== -1) { return 'https://missmonribs.getappeasy.com/store/api/v1/'; } return GURL.base_api_url(); } /* Open */ var timerAdjustOpen = 0; $inregisterPopupTypeSirikhu.isOpen = false; $inregisterPopupTypeSirikhu.open = function() { $inregisterPopupTypeSirikhu.resetViewPassword('register-password-v1'); $inregisterPopupTypeSirikhu.validateRegister().reset(); $(".register_overlay").addClass("is_open"); $('html').css({ 'overflow-y': 'scroll', 'overflow': 'hidden' }); $('body').css({ 'overflow': 'auto', 'position': 'unset' }); timerAdjustOpen = setTimeout(function() { $(".register.from_background").addClass("is_open"); }, 100); $inregisterPopupTypeSirikhu.getLocation(2, 231, 1, 100, '', '', function(dataLocation) { console.log("$inregisterPopupTypeSirikhu : open : dataLocation : ", dataLocation); for (var i = 0; i < dataLocation.length; i++) { console.log("2 $inregisterPopupTypeSirikhu : open : for : dataLocation[" + i + "] : ", dataLocation[i]); $('#register-province-v1').append(''); } }); $(document).keypress(function(e) { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode == '13') { $inregisterPopupTypeSirikhu.submitRegister(); } }); }; /* Open */ /* Close */ $inregisterPopupTypeSirikhu.close = function() { $(".register_overlay").removeClass("is_open"); $(".register.from_background").removeClass("is_open"); $('html').css({ 'overflow-y': 'unset', 'overflow': 'unset' }); $('body').css({ 'overflow': 'auto', 'position': 'relative' }); }; /* Close */ /* shake */ $inregisterPopupTypeSirikhu.shake = function() { $(".register.from_background.is_open").addClass('shake'); timerAdjustOpen = setTimeout(function() { $(".register.from_background.is_open").removeClass('shake'); }, 100); } /* shake */ /* login */ $inregisterPopupTypeSirikhu.login = function() { $inregisterPopupTypeSirikhu.close(); $inregisterPopupTypeSirikhu.helper.registerUnDone(); $inloginPopupTypeSirikhu.open(); } /* login */ /* toHome */ $inregisterPopupTypeSirikhu.toHome = function() { $inregisterPopupTypeSirikhu.helper.registerUnDone(); window.location.href = 'home'; }; /* toHome */_ui_share_app.factory('$componentSearchProduct', function componentSearchProduct($routeParams, $timeout) { return });_ui_share_app.directive('componentSearchProductGrip', function($rootScope, $routeParams, $location) { var templateName = 'componentSearchProductGrip'; var componentMain = 'componentSearchProduct'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', databutton: '@databutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.gripautobiz.php'; $scope.tireCharacteristics = [{ type: "size_width", title: "หน้ายาง", dataSend: { 'type': 'size_width', }, select: "", dataArray: [] }, { type: "size_series", title: "ซีรี่ส์ยาง", dataSend: { 'type': 'size_series', 'size_width': "" }, select: "", dataArray: [] }, { type: "size_diameter", title: "ขนาดกะทะล้อ", dataSend: { 'type': 'size_diameter', 'size_width': "", 'size_series': "" }, select: "", dataArray: [] }]; $scope.getDataArray = function() { var getFunction = { consoleLog: function(name, data) { var log = false; if (log) { console.log(name, data); } }, changeSelectApi: function(number) { var _self = this; _self.getParams($scope.tireCharacteristics[number].dataSend, function(params) { _self.consoleLog("changeSelectApi : params : ", params); _self.getDataApi($scope.thirdPartyApi, params, function(output) { _self.consoleLog("changeSelectApi : getDataApi : output : ", output); $scope.$apply(function() { $scope.tireCharacteristics[number].dataArray = output.data; }); }); }); }, changeSelect: function(number) { var _self = this; _self.consoleLog("changeSelect : ", number); if (number == 1) { for (var i = 0; i < 2; i++) { $scope.tireCharacteristics[number + i].select = ""; $scope.tireCharacteristics[number + i].dataArray = []; } $scope.tireCharacteristics[number].dataSend = { 'type': 'size_series', 'size_width': $scope.tireCharacteristics[number - 1].select }; if ($scope.tireCharacteristics[number - 1].select != "") { _self.changeSelectApi(number); } } else if (number == 2) { for (var i = 0; i < 1; i++) { $scope.tireCharacteristics[number + i].select = ""; $scope.tireCharacteristics[number + i].dataArray = []; } $scope.tireCharacteristics[number].dataSend = { 'type': 'size_diameter', 'size_width': $scope.tireCharacteristics[number - 2].select, 'size_series': $scope.tireCharacteristics[number - 1].select }; if ($scope.tireCharacteristics[number - 2].select != "" && $scope.tireCharacteristics[number - 1].select != "") { _self.changeSelectApi(number); } } }, getParams: function(dataSend, callback) { var params = { params: dataSend }; callback(params); }, getDataApi: function(api, params, callback) { GAEAPI.directNativeAjax(api, params).then(function(output) { callback(output); }); }, main: function() { var _self = this; _self.getParams($scope.tireCharacteristics[0].dataSend, function(params) { _self.consoleLog("getParams : params : ", params); _self.getDataApi($scope.thirdPartyApi, params, function(output) { _self.consoleLog("getParams : getDataApi : output : ", output); $scope.$apply(function() { $scope.tireCharacteristics[0].dataArray = output.data; }); }); }); }, windowLocationUrl: function(url) { if ($scope.tireCharacteristics[0].select != "" && $scope.tireCharacteristics[1].select != "" && $scope.tireCharacteristics[2].select != "") { var strHref = 'search-products/'; strHref += $scope.tireCharacteristics[0].select + "-" + $scope.tireCharacteristics[1].select + "-" + $scope.tireCharacteristics[2].select; /* strHref += '?base_shop_name=gripautobiz'; */ $location.url(strHref).replace(); } } } return getFunction; }; $scope.getDataArray().main(); }; return promise; });_ui_share_app.directive('componentSearchProductsGrip', function($rootScope, $routeParams, $location) { var templateName = 'componentSearchProductsGrip'; var componentMain = 'componentSearchProduct'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', mini: '@mini', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.gripautobiz.php'; /* search */ $scope.search = ""; $scope.tireCharacteristics = [{ type: "size_width", title: "หน้ายาง", dataSend: { 'type': 'size_width', }, select: "", dataArray: [] }, { type: "size_series", title: "ซีรี่ส์ยาง", dataSend: { 'type': 'size_series', 'size_width': "" }, select: "", dataArray: [] }, { type: "size_diameter", title: "ขนาดกะทะล้อ", dataSend: { 'type': 'size_diameter', 'size_width': "", 'size_series': "" }, select: "", dataArray: [] }]; $scope.brand = [{ api: "referral/lists", title: "ยี่ห้อยาง", dataSend: { 'txt_referral_type_id': "12", 'cur_page': "1", 'per_page': "150", 'txt_sortby': 'referral_name_z-a', 'skip_cache': '1' }, select: "", selectB: "", dataArray: [] }]; /* search */ /* product */ $scope.renderTxtFilterResult = ""; $scope.dataArray = []; $scope.dataArrayState = { load: false, done: false }; $scope.dataSendProduct = { dataSend: { 'type': 'filter_product', 'search_type': "size", 'size_width': "", 'size_series': "", 'size_diameter': "", 'per_page': 10, 'page': 1, 'filter': "", 'no_zero': "1" }, dataPage: [] }; /* product */ $scope.getDataArray = function() { var getFunction = { consoleLog: function(name, data) { var log = true; if (log) { console.log(name, data); } }, windowLocationUrl: function(url) { if ($scope.tireCharacteristics[0].select != "" && $scope.tireCharacteristics[1].select != "" && $scope.tireCharacteristics[2].select != "") { var strHref = 'search-products/'; strHref += $scope.tireCharacteristics[0].select + "-" + $scope.tireCharacteristics[1].select + "-" + $scope.tireCharacteristics[2].select + "-" + $scope.brand[0].select; $location.url(strHref).replace(); } }, stateData: function(loadIn, doneIn) { var state = { load: loadIn, done: doneIn }; return state; }, changeSelectApi: function(number) { var _self = this; _self.getParams($scope.tireCharacteristics[number].dataSend, function(params) { _self.consoleLog("changeSelectApi : params : ", params); _self.getDataApi($scope.thirdPartyApi, params, function(output) { _self.consoleLog("changeSelectApi : getDataApi : output : ", output); $scope.$apply(function() { $scope.tireCharacteristics[number].dataArray = output.data; }); }); }); }, resetSelect: function(array, number) { var _self = this; for (var i = 0; i < array; i++) { _self.consoleLog("resetSelect : for : i : ", number + i); _self.consoleLog("resetSelect : for : $scope.tireCharacteristics : ", $scope.tireCharacteristics[number + i]); $scope.tireCharacteristics[number + i].select = ""; $scope.tireCharacteristics[number + i].dataArray = []; } }, changeSelect: function(number, from) { var _self = this; _self.consoleLog("changeSelect : ", number); if (number == 1) { if (from == 'html') { _self.resetSelect(2, number); } $scope.tireCharacteristics[number].dataSend = { 'type': 'size_series', 'size_width': $scope.tireCharacteristics[number - 1].select }; if ($scope.tireCharacteristics[number - 1].select != "") { _self.changeSelectApi(number); } } else if (number == 2) { if (from == 'html') { _self.resetSelect(1, number); } $scope.tireCharacteristics[number].dataSend = { 'type': 'size_diameter', 'size_width': $scope.tireCharacteristics[number - 2].select, 'size_series': $scope.tireCharacteristics[number - 1].select }; if ($scope.tireCharacteristics[number - 2].select != "" && $scope.tireCharacteristics[number - 1].select != "") { _self.changeSelectApi(number); } } }, getDataSend: function(search, callback) { var _self = this; _self.getSearchArray(0, function(size_width) { _self.consoleLog("getDataSend : size_width : ", size_width); _self.getSearchArray(1, function(size_series) { _self.consoleLog("getDataSend : size_series : ", size_series); _self.getSearchArray(2, function(size_diameter) { _self.consoleLog("getDataSend : size_diameter : ", size_diameter); _self.checkFormatSizeDiameter(size_diameter, function(size_diameter) { _self.consoleLog("getDataSend : checkFormatSizeDiameter : size_diameter : ", size_diameter); var dataSend = { 'type': 'filter_product', 'search_type': "size", 'size_width': size_width, 'size_series': size_series, 'size_diameter': size_diameter, 'brand_id': $scope.brand[0].select, 'per_page': 10, 'page': (typeof _self.getSearch().page !== 'undefined' && typeof _self.getSearch().page !== '') ? parseInt(_self.getSearch().page) : 1, 'filter': "", 'no_zero': "1" } callback(dataSend); }); }); }); }); }, getParams: function(dataSend, callback) { var params = { params: dataSend }; callback(params); }, getDataApi: function(api, params, callback) { GAEAPI.directNativeAjax(api, params).then(function(output) { callback(output); }); }, getSearch: function() { var params = $routeParams; return params; }, getSearchArray: function(number, callback) { var params = $routeParams; var search = params.search.split('-'); callback((typeof search[number] !== 'undefined') ? search[number] : '') }, checkFormat: function(input, callback) { var returnText = input.replace(/\?/g, " ").replace(/\&/g, " ").replace(/\#/g, " ").replace(/\-/g, " ").replace(/\!/g, " ").replace(/\*/g, " ").replace(/\:/g, " ").replace(/ /g, " "); callback(returnText); }, checkFormatSizeDiameter: function(input, callback) { var returnText = input.replace(/\R/g, ""); callback(returnText); }, renderFilterResultNumber: function(currentPage, totalItems, totalThisRequest) { var i = 1; var m = 10; if (currentPage > 1) { i = (currentPage - 1) + "1"; m = parseInt(i) + (totalThisRequest - 1); } $scope.renderTxtFilterResult = "ผลลัพธ์ " + i + "-" + m + " จาก " + totalItems + " รายการ "; }, getPageArray: function(dataInput, per_page) { console.log('getPageArray : dataInput : ', dataInput); var pages = parseInt(dataInput.data.total_items) / per_page; console.log('getPageArray : pages : ', pages); for (var i = 0; pages > i; i++) { $scope.dataSendProduct.dataPage.push(i + 1); } }, getApi: function(api, dataSend, callback) { GAEAPI.get(api, dataSend, $scope).then(function(output) { callback(output); }); }, checkProcess: function(product_id) { return (UiCart.delegate.product.isSelected(product_id)) ? 'ดูรถเข็น' : 'สั่งซื้อสินค้า'; }, checkDataButton: function(product_id, data_button) { var btn = data_button; var useSecondary = (btn.indexOf('econdary') != -1) ? true : false; var color = (!useSecondary) ? 'primary_darkest' : 'secondary_darkest'; return (UiCart.delegate.product.isSelected(product_id)) ? color : ''; }, locationUrl: function(product_id, title) { return (UiCart.delegate.product.isSelected(product_id)) ? $location.url('viewcart').replace() : $location.url('product-detail/' + product_id + '-' + $scope.buildTitleUrl(title)).replace(); }, main: function() { var _self = this; _self.checkFormat(_self.getSearch().search, function(returnText) { _self.consoleLog("checkFormat : returnText : ", returnText); $scope.search = returnText.split(" ", 3).join(" "); }); _self.getSearchArray(3, function(brand_select) { _self.consoleLog("getSearchArray[3] : ", brand_select); $scope.brand[0].select = brand_select; $scope.brand[0].selectB = brand_select; }); for (var i = 0; i < $scope.tireCharacteristics.length; i++) { _self.consoleLog("getSearchArray : $scope.tireCharacteristics : ", i); _self.getSearchArray(i, function(search) { _self.consoleLog("getSearchArray : search : ", search); $scope.tireCharacteristics[i].select = search; _self.changeSelect(i, 'js'); }); } _self.getParams($scope.tireCharacteristics[0].dataSend, function(params) { _self.consoleLog("getParams : params : ", params); _self.getDataApi($scope.thirdPartyApi, params, function(output) { _self.consoleLog("getParams : getDataApi : output : ", output); $scope.$apply(function() { $scope.tireCharacteristics[0].dataArray = output.data; }); }); }); $scope.dataArrayState = _self.stateData(true, false); _self.getDataSend(_self.getSearch().search, function(dataSend) { _self.consoleLog("getDataSend : dataSend : ", dataSend); $scope.dataSendProduct.dataSend = dataSend; _self.getParams($scope.dataSendProduct.dataSend, function(params) { _self.consoleLog("getDataSend : getParams : params : ", params); _self.getDataApi($scope.thirdPartyApi, params, function(output) { _self.consoleLog("getDataSend : getParams : getDataApi : output : ", output); $scope.$apply(function() { $scope.dataArray = output.data.data_lists; _self.renderFilterResultNumber(1, output.data.total_items, output.data.data_lists.length); _self.getPageArray(output, $scope.dataSendProduct.dataSend.per_page); $scope.dataArrayState = _self.stateData(false, true); }); }); }); }); _self.getApi($scope.brand[0].api, $scope.brand[0].dataSend, function(output) { _self.consoleLog("getApi : referral/lists : api : ", $scope.brand[0].api); _self.consoleLog("getApi : referral/lists : dataSend : ", $scope.brand[0].dataSend); _self.consoleLog("getApi : referral/lists : output : ", output); $scope.brand[0].dataArray = output.data.dataList; }); } } return getFunction; }; $scope.setPages = function(input) { var params = $routeParams; var path = { page: params.page, search: params.search, }; if (input == 'back') { if (($scope.cur_page - 1) != 0) { var strHref = 'search-products/'; strHref += $scope.getDataArray().getSearch().search; strHref += '?page=' + ($scope.dataSendProduct.dataSend.page - 1); /* strHref += '&base_shop_name=gripautobiz'; */ $location.url(strHref).replace(); } } else if (input == 'next') { if ($scope.dataSendProduct.dataSend.page < $scope.dataSendProduct.dataPage.length) { var strHref = 'search-products/'; strHref += $scope.getDataArray().getSearch().search; strHref += '?page=' + ($scope.dataSendProduct.dataSend.page + 1); /* strHref += '&base_shop_name=gripautobiz'; */ $location.url(strHref).replace(); } } }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.getDataArray().main(); }; return promise; }); _ui_share_app.directive('componentSearchResult', function ($rootScope, $location, $routeParams, shareService) { var templateName = 'componentSearchResult'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { template: '@template', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window, $http) { /* template : default */ /* template : default */ /* template : default */ var scope = $scope; $scope._param = $routeParams.search; $scope.getTemplate = function () { return _ui_share_host + templateName + '/template/' + $scope.template + '.html'; }; $scope.findHilightForTires = function (txt) { var reg = new RegExp($scope.dataQuery, 'i'); var str = txt; var re = str.replace(reg, '$&'); return re; }; $scope.continuePage = false; $scope.assetsPath = 'extensions/themes/assets/'; $scope._uiSearchOnClose = function () { UiSearchBox.delegate.modal.close(); $scope._uiSearchReset(); }; $scope.$watch('_params', function (newValue, oldValue) { if (newValue){ // $scope._uiSearchStart(newValue); // $scope.getDataProduct(newValue) } }); var typingTimer = null; $scope._uiSearchChange = function (modelStr) { console.log('_uiSearchStart', modelStr.toString().length); clearTimeout(typingTimer); typingTimer = setTimeout(function () { if (modelStr.toString().length >= 3) { $scope._uiSearchStart(modelStr.toString()); } }, 1000); }; $scope._uiSearchReset = function () { $scope.dataQuery = ''; $scope.dataArray = []; $scope.dataRequest = 1; $scope.dataIsLoad = false; $scope.dataIsDone = false; }; $scope.pagination_data_custom = {}; $scope.buildPaginationParameterCustom = function (data) { if (data === false) { $scope.pagination_data_custom = {}; return; } console.log("vm.pagination_data_custom: vm.routeParams", $routeParams, $location.search()); var generateRangeArray = function (total_items, per_page, cur_page) { console.log("vm.pagination_data_custom : generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data_custom.cur_page = parseInt(data.cur_page); $scope.pagination_data_custom.per_page = parseInt(data.per_page); $scope.pagination_data_custom.result_rows = parseInt(data.dataList.length); $scope.pagination_data_custom.total_rows = parseInt(data.total_rows); $scope.pagination_data_custom.max_page = Math.ceil($scope.pagination_data_custom.total_rows / $scope.pagination_data_custom.per_page); $scope.pagination_data_custom.prev_page = parseInt($scope.pagination_data_custom.cur_page - 1); $scope.pagination_data_custom.next_page = parseInt($scope.pagination_data_custom.cur_page + 1); $scope.pagination_data_custom.page_array = generateRangeArray($scope.pagination_data_custom.total_rows, $scope.pagination_data_custom.per_page, $scope.pagination_data_custom.cur_page); console.log('vm.pagination_data_custom', $scope.pagination_data_custom); }; $scope.referral_support = { relation:[], relation_txt_array:[], id:[] }; $scope.buildReferralSupportData = function(referralId){ console.log("buildReferralSupportData",referralId); var dataSend = { 'txt_referral_id': referralId }; $http.get(GURL.base_api_url() +'referral/id',{params:dataSend}).then(function(e){ var res = e.data; if(res.ok == 1){ $scope.referral_support.id[0] = res.data; } }); $http.get(GURL.base_api_url() +'referral/relation',{params:dataSend}).then(function(e){ var res = e.data; if(res.ok == 1){ $scope.referral_support.relation = res.data; for(var i = 0; i < res.data.length; i++){ $scope.referral_support.relation_txt_array.push(res.data[i].referral_name); } } }); }; $scope.dataQuery = (typeof $routeParams.query !== 'undefined' && $routeParams.query !== '') ? $routeParams.query : ''; $scope.dataArray = []; $scope.dataRequest = (typeof $routeParams.page !== 'undefined' && $routeParams.page !== '') ? $routeParams.page : ''; ; $scope.dataIsLoad = false; $scope.dataIsDone = false; $scope.dataLastQuery = ''; $scope._uiSearchStart = function (queryString) { var filterJson = { 'badge_id_array':[18], 'search': $scope.dataQuery }; var dataSend = { cur_page: $scope.dataRequest, per_page: 10, txt_sortby: 'product_lastest_create', txt_filter_json: JSON.stringify(filterJson) }; $scope.dataIsLoad = true; $scope.dataIsDone = false; $http.get(GURL.base_api_url() + 'product/lists', {params: dataSend}).then(function (e) { var res = e.data; $scope.dataIsLoad = false; $scope.dataIsDone = true; $scope.dataTotalPage = Math.ceil(res.data.total_rows / 10); $scope.dataTotalList = res.data.total_rows; console.log('_uiSearchStart', dataSend, res); if (res.data.dataList.length > 0) { if ($scope.dataArray.length > 0 && dataSend.page != 1) { var curData = $scope.dataArray; $scope.dataArray = curData.concat(res.data.dataList); } else { $scope.dataArray = res.data.dataList; } $scope.dataLastQuery = $scope.dataQuery; } $scope.buildPaginationParameterCustom(res.data); }); }; if ($scope.type == 'default') { $scope._uiSearchStart($scope.dataQuery); } $scope._uiSearchLoadMore = function () { if ($scope.dataLastQuery == $scope.dataQuery) { $scope.dataRequest++; } else { $scope.dataRequest = 1; } $scope._uiSearchStart($scope.dataQuery); }; $scope._uiSearchContinueCheck = function () { $.get(GURL.base_url() + "search-result", function (data) { var dataStr = data.toLowerCase(); if (dataStr.indexOf('not found!') === -1) { $scope.continuePage = true; } else { $scope.continuePage = false; } }); }; $scope._uiSearchContinue = function () { $.get(GURL.base_url() + "search-result", function (data) { var dataStr = data.toLowerCase(); if (dataStr.indexOf('not') !== -1 && dataStr.indexOf('found') !== -1) { $scope._uiSearchOnClose(); window.location.href = GURL.base_url() + "search-result?page=1&per_page=10&query=" + $scope.dataLastQuery; } }); }; $scope.buildFilterUrl = function (exceptionalKey) { var a = ''; angular.forEach($routeParams, function (item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.routeFilterPage = function (pageNumber) { return window.location.href = 'search-result?page=' + pageNumber + $scope.buildFilterUrl(); }; /* template : first */ /* template : first */ /* template : first */ function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function () { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; if ($scope.template == 'first') { /* init jqueryui slider (require juqery ui js,css) */ $timeout(function () { console.log("changeRangePrice : -1"); $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function (event, ui) { $scope.$apply(function () { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); }, 1000); }; /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function (m) { $scope.filterSortData = m; $timeout(function () { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || $scope.viewRouteParams().per_page || '12'; $scope.changefilterPerPageData = function (m) { $scope.filterPerPageData = m; $timeout(function () { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function (isChecked, badgeId) { console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function () { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function (v) {}; $scope.doFilterBy = function (isChecked, badgeId) {}; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function (isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function () { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function (index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function () { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function (id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function (isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function (isChecked, id) { console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function () { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function () { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function (e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function () { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function (e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function () { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function (e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function () { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function () { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.getDataProduct = function () { var dupplicateRemove = function (curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } /* check sort */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } /* check search query */ if (typeof $routeParams.query !== 'undefined' && $routeParams.query != '') { json_filter.search = $routeParams.query; } if (typeof $routeParams.search !== 'undefined' && $routeParams.search != '') { json_filter.search = $routeParams.search; } /* check tags */ if (typeof $routeParams.tags !== 'undefined' && $routeParams.tags != '') { json_filter.tags = $routeParams.tags; } var dataSend = { /*'cur_page': $scope.fetchTime,*/ 'cur_page': (typeof $routeParams.page !== 'undefined' && $routeParams.page != '') ? $routeParams.page : 1, 'per_page': $scope.filterPerPageData || 10, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; GAEAPI.get('product/lists', dataSend).then(function (e) { console.log("getDataProduct: dataSend", dataSend); console.log("getDataProduct: e", e); $scope.data_product_done = true; if (e.ok == 1 && e.data.dataList.length) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); } else { $scope.data_product = e.data.dataList; } } else if (!e.data.dataList.length) { } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } $scope.buildPaginationParameterCustom(e.data); $scope.changeRangePrice(); /* check referral id */ if(typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id !== '' && $routeParams.referral_id != 0){ $scope.buildReferralSupportData($routeParams.referral_id); } }); }; $scope.viewType = 'grid'; /* list / grid */ /* change min and max price by current data */ $scope.changeRangePrice = function () { if (!$scope.data_product.length) { return; } function getMinOfArray(numArray) { return Math.min.apply(null, numArray); } function getMaxOfArray(numArray) { return Math.max.apply(null, numArray); } var p = []; angular.forEach($scope.data_product, function (item, key) { this.push(parseInt(item.product_price)); }, p); console.log("changeRangePrice : 0", p, $('div#slider-range').hasClass('ui-slider')); if ($('div#slider-range').hasClass('ui-slider')) { $scope.rangeConfig.min = getMinOfArray(p); $scope.rangeConfig.max = getMaxOfArray(p); $('div#slider-range').slider("option", "min", getMinOfArray(p)); $('div#slider-range').slider("option", "max", getMaxOfArray(p)); console.log("changeRangePrice : 1", $scope.rangeConfig); } }; /* Check if seo enable */ $scope.checkSeo = function () { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function (id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function (string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function (productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function (strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function (id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function () { var buildBadge = function () { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function () {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* category name of this category */ badge: badgeIdArray, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'search-result'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } if (typeof $routeParams.query !== 'undefined' && $routeParams.query !== '') { strHref += '&query=' + $routeParams.query; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("result?") == -1) { strHref = strHref.replace("search-result&", "search-result?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function () { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function () { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; if ($scope.template === 'first' || $scope.template === 'first-lightmax') { $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.buildParamsBrand(); } $rootScope.$on('$routeChangeStart', function (event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function () { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', {txt_referral_type_id: 11}, $scope).then(function (e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } }; return promise; }); _ui_share_app.directive('componentSendMailPageA', function ($rootScope, $routeParams) { var templateName = 'componentSendMailPageA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', texthead: '@texthead', imgpath: '@imgpath', contact: '@contact', stylebutton: '@stylebutton', fontcolor: '@fontcolor', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.stylebutton = (typeof $scope.stylebutton !== 'undefined') ? $scope.stylebutton : 'filled_button_small'; $scope.shopname = ""; $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopname = e.data.shop_name; $scope.contact_email = e.data.shop_extend_data.contact_email; } }); }; $scope.getShopCurrent(); /* Form Params */ $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_line_id = ""; $scope.input_line_id_valid = false; // $scope.input_message = ""; // $scope.input_message_valid = false; // $scope.input_topic = ""; // $scope.input_topic_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; /* Watch Value */ $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_number', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_number_valid = false; return; } $scope.input_number_valid = true; }); $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_line_id', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_line_id_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_line_id_valid = true; } else { $scope.input_line_id_valid = false; } }); /* $scope.$watch('input_topic', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_topic_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_topic_valid = true; } else { $scope.input_topic_valid = false; } }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); */ /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { // alert("กรุณากรอกอีเมลของท่านให้ถูกต้อง"); } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.shopname !== "" && $scope.contact_email !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.shopname); formData.append('input_owner_contact', $scope.contact_email); console.log("pass!", formData , $scope.shopname ,$scope.contact_email); $.ajax({ url: _ui_share_host + '../sendgrid/send-email_npd.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_line_id = ""; $scope.input_line_id_valid = false; // $scope.input_message = ""; // $scope.input_message_valid = false; // $scope.input_topic = ""; // $scope.input_topic_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_name = ""; $scope.input_name_valid = false; $scope.input_email = ""; $scope.input_email_valid = false; $scope.input_line_id = ""; $scope.input_line_id_valid = false; // $scope.input_message = ""; // $scope.input_message_valid = false; // $scope.input_topic = ""; // $scope.input_topic_valid = false; $scope.input_number = ""; $scope.input_number_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $scope.showDebug = function() { return (typeof $routeParams.debugcontact !== 'undefined') ? true : false; }; }; return promise; }); _ui_share_app.factory('$componentShopBranch', function componentShopBranch($routeParams, $timeout) { return });_ui_share_app.directive('componentShopBranchDetailA', function($rootScope, $routeParams) { var templateName = 'componentShopBranchDetailA'; var componentMain = 'componentShopBranch'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.map = { zoom: "15", positionLat: "0", positionLng: "0", centerLat: "0", centerLng: "0.008" }; $scope.dataShopBranchId = []; $scope.dataShopBranchIdMobilePhone = []; $scope.getShopBranchIdState = { load: true, done: false }; $scope.googleMap = function() { var map = { initMap: function(mapId, zoom, positionLat, positionLng, centerLat, centerLng, infoId, dataShopBranchId) { var _self = this; map = new google.maps.Map(document.getElementById(mapId), { zoom: parseFloat(zoom), center: new google.maps.LatLng(parseFloat(positionLat) - parseFloat(centerLat), parseFloat(positionLng) - parseFloat(centerLng)), mapTypeId: 'roadmap' }); var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; var icons = { info: { name: 'info', icon: 'https://image.getappeasy.com/src/images/2000/1242/0874/242874t1538392679.png' } }; var features = [{ position: new google.maps.LatLng(parseFloat(positionLat), parseFloat(positionLng)), type: 'info' }]; features.forEach(function(feature) { var marker = new google.maps.Marker({ position: feature.position, icon: icons[feature.type].icon, map: map }); }); _self.innerHTML(infoId, dataShopBranchId); }, innerHTML: function(infoId, dataShopBranchId) { var info = document.getElementById(infoId); /*var cover_branch = document.createElement('div'); cover_branch.className = "cover_branch";*/ /*var icon = document.createElement('img'); icon.className = "icon"; icon.src = dataShopBranchId.shop_branch_primary_image[0].image_url;*/ /*cover_branch.appendChild(icon); info.appendChild(cover_branch);*/ map.controls[google.maps.ControlPosition.LEFT_TOP].push(info); } } return map; }; $scope.getBranch = function() { var branch = { stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, viewRouteParams: function(callback) { var branch_id = (typeof $routeParams.branch_id !== 'undefined' && typeof $routeParams.branch_id !== '') ? parseInt($routeParams.branch_id) : 0; if (branch_id != 0) { callback(branch_id); } else { callback(branch_id); } }, getShopBranchId: function(shop_branch_id, callback) { var dataSend = { 'txt_shop_branch_id': shop_branch_id }; // console.log('getShopBranchId : dataSend : ', dataSend); GAEAPI.get('shop_branch/id', dataSend).then(function(output) { // console.log('getShopBranchId : output : ', output); callback(output); }); }, mobilePhone: function(mobile_phone, callback) { var mobile_phone_array = []; if (mobile_phone.length > 0) { mobile_phone_array = mobile_phone.split(","); } callback(mobile_phone_array); }, displayTelCode: function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }, branchMapLocation: function(shop_branch_map_location_array, callback) { var lat = "0"; var lng = "0"; if (shop_branch_map_location_array.length != 0) { lat = shop_branch_map_location_array[0].lat; lng = shop_branch_map_location_array[0].lng; } callback(lat, lng); }, linkMap: function() { var link = 'https://www.google.co.th/maps?q=' + $scope.map.positionLat + ',' + $scope.map.positionLng; window.open(link, '_blank'); }, displayDayByIndex: function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }, main: function() { var _self = this; $scope.getShopBranchIdState = _self.stateData(true, false); _self.viewRouteParams(function(branch_id) { // console.log('branch_id : ', branch_id); _self.getShopBranchId(branch_id, function(output) { $scope.dataShopBranchId = output.data; _self.branchMapLocation(output.data.shop_branch_map_location_array, function(lat, lng) { $scope.map.positionLat = lat; $scope.map.positionLng = lng; }); _self.mobilePhone(output.data.shop_branch_address.address_extend_data.mobile_phone, function(mobile_phone_array) { $scope.dataShopBranchIdMobilePhone = mobile_phone_array; }); $scope.getShopBranchIdState = _self.stateData(false, true); var myLocationTimer = setInterval(function() { window.clearInterval(myLocationTimer); $scope.googleMap().initMap('map', $scope.map.zoom, $scope.map.positionLat, $scope.map.positionLng, $scope.map.centerLat, $scope.map.centerLng, 'branch_info', $scope.dataShopBranchId); }, 500); }); }); } } return branch; }; $scope.getBranch().main(); }; return promise; });_ui_share_app.directive('componentShopBranchListsA', function($rootScope, $routeParams) { var templateName = 'componentShopBranchListsA'; var componentMain = 'componentShopBranch'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', mini: '@mini', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataPage = []; $scope.cur_page = 1; $scope.per_page = (typeof $scope.mini !== 'undefined' && typeof $scope.mini !== '') ? parseInt($scope.mini) : 10; $scope.dataShopBranchLists = []; $scope.getShopBranchListsState = { load: true, done: false }; $scope.getBranch = function() { var branch = { getPage: function(callback) { var params = $routeParams; $scope.cur_page = (typeof params.page !== 'undefined' && typeof params.page !== '') ? parseInt(params.page) : 1; callback(params); }, stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, getShopBranchLists: function(cur_page, per_page, callback) { var filter_json = {}; var dataSend = { 'cur_page': cur_page, 'per_page': per_page, 'txt_filter_json': JSON.stringify(filter_json) }; // console.log('getShopBranchLists : dataSend : ', dataSend); GAEAPI.get('shop_branch/lists', dataSend).then(function(output) { // console.log('getShopBranchLists : output : ', output); callback(output); }); }, getPageArray: function(dataInput, per_page) { // console.log('getPageArray : dataInput : ', dataInput); var pages = dataInput.data.total_rows / per_page; // console.log('getPageArray : pages : ', pages); for (var i = 0; pages > i; i++) { $scope.dataPage.push(i + 1); } }, main: function() { var _self = this; $scope.getShopBranchListsState = _self.stateData(true, false); _self.getPage(function(params) { _self.getShopBranchLists($scope.cur_page, $scope.per_page, function(output) { _self.getPageArray(output, $scope.per_page); $scope.dataShopBranchLists = output.data.dataList; $scope.getShopBranchListsState = _self.stateData(false, true); }) }); } } return branch; }; $scope.getBranch().main(); }; return promise; });_ui_share_app.directive('componentShopBranchListsB', function($rootScope, $routeParams) { var templateName = 'componentShopBranchListsB'; var componentMain = 'componentShopBranch'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', mini: '@mini', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataPage = []; $scope.cur_page = 1; $scope.per_page = (typeof $scope.mini !== 'undefined' && typeof $scope.mini !== '') ? parseInt($scope.mini) : 10; $scope.urlgooglemap = []; $scope.urllinkmap = []; $scope.dataShopBranchLists = []; $scope.getShopBranchListsState = { load: true, done: false }; $scope.getBranch = function() { var branch = { getPage: function(callback) { var params = $routeParams; $scope.cur_page = (typeof params.page !== 'undefined' && typeof params.page !== '') ? parseInt(params.page) : 1; callback(params); }, stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, getShopBranchLists: function(cur_page, per_page, callback) { var filter_json = {}; var dataSend = { 'cur_page': cur_page, 'per_page': per_page, 'txt_filter_json': JSON.stringify(filter_json) }; // console.log('getShopBranchLists : dataSend : ', dataSend); GAEAPI.get('shop_branch/lists', dataSend).then(function(output) { // console.log('getShopBranchLists : output : ', output); callback(output); }); }, getPageArray: function(dataInput, per_page) { // console.log('getPageArray : dataInput : ', dataInput); var pages = dataInput.data.total_rows / per_page; // console.log('getPageArray : pages : ', pages); for (var i = 0; pages > i; i++) { $scope.dataPage.push(i + 1); } }, placeNo: function(i, lat, lng) { $scope.urlgooglemap[i] = 'https://www.google.com/maps/embed/v1/place?q=' + lat + ',' + lng + '&key=AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18'; }, pulllinkMap: function(i, lat, lng) { $scope.urllinkmap[i] = 'https://www.google.co.th/maps?q=' + lat + ',' + lng; }, displayTelCode: function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }, linkMap: function(i) { var link = $scope.urllinkmap[i]; window.open(link, '_blank'); }, main: function() { var _self = this; $scope.getShopBranchListsState = _self.stateData(true, false); _self.getPage(function(params) { _self.getShopBranchLists($scope.cur_page, $scope.per_page, function(output) { _self.getPageArray(output, $scope.per_page); $scope.dataShopBranchLists = output.data.dataList; for (var i = 0; i < $scope.dataShopBranchLists.length; i++) { _self.placeNo(i, $scope.dataShopBranchLists[i].shop_branch_map_location_array[0].lat, $scope.dataShopBranchLists[i].shop_branch_map_location_array[0].lng); _self.pulllinkMap(i, $scope.dataShopBranchLists[i].shop_branch_map_location_array[0].lat, $scope.dataShopBranchLists[i].shop_branch_map_location_array[0].lng); } $scope.getShopBranchListsState = _self.stateData(false, true); }) }); } } return branch; }; $scope.getBranch().main(); }; return promise; });_ui_share_app.factory('$componentShopDealer', function componentShopDealer($routeParams, $timeout) { return });_ui_share_app.directive('componentShopDealerDetailA', function($rootScope, $routeParams) { var templateName = 'componentShopDealerDetailA'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', key: '@key', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.map = { zoom: "15", positionLat: "0", positionLng: "0", centerLat: "0", centerLng: "0.008", innerHTML: "" }; $scope.dataShopDealerId = []; $scope.dataShopDealerIdMobilePhone = []; $scope.getShopDealerIdState = { load: true, done: false }; var w = angular.element($window); $scope.getWindowDimensions = function() { return { 'h': w.height(), 'w': w.width() }; }; w.bind('resize', function() { $scope.$apply(); }); $scope.$watch($scope.getWindowDimensions, function(newValue, oldValue) { $scope.windowHeight = newValue.h; $scope.windowWidth = newValue.w; var viewMap = ($scope.windowWidth > 991) ? "0.008" : "0"; if ($scope.map.centerLng != viewMap) { $scope.map.centerLng = viewMap; $scope.getDealer().main(); } }, true); $scope.googleMap = function() { var map = { loadScript: function(key, callback) { var file_url = 'https://maps.googleapis.com/maps/api/js?key=' + key + '&v=3.31'; jQuery.ajax({ url: file_url, dataType: 'script', success: callback, async: true }); }, initMap: function(mapId, zoom, positionLat, positionLng, centerLat, centerLng, infoId, dataShopBranchId) { var _self = this; map = new google.maps.Map(document.getElementById(mapId), { zoom: parseFloat(zoom), center: new google.maps.LatLng(parseFloat(positionLat) - parseFloat(centerLat), parseFloat(positionLng) - parseFloat(centerLng)), mapTypeId: 'roadmap' }); var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; var icons = { info: { name: 'info', icon: 'https://image.getappeasy.com/src/images/2000/1242/0874/242874t1538392679.png' } }; var features = [{ position: new google.maps.LatLng(parseFloat(positionLat), parseFloat(positionLng)), type: 'info' }]; features.forEach(function(feature) { var marker = new google.maps.Marker({ position: feature.position, icon: icons[feature.type].icon, map: map }); }); _self.innerHTML(infoId, dataShopBranchId); }, innerHTML: function(infoId, dataShopBranchId) { var info = document.getElementById(infoId); if ($scope.map.innerHTML == "") { $scope.map.innerHTML = info; } map.controls[google.maps.ControlPosition.LEFT_TOP].push($scope.map.innerHTML); } } return map; }; $scope.getDealer = function() { var dealer = { stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, viewRouteParams: function(callback) { var dealer_id = (typeof $routeParams.dealer_id !== 'undefined' && typeof $routeParams.dealer_id !== '') ? parseInt($routeParams.dealer_id) : 0; if (dealer_id != 0) { callback(dealer_id); } else { callback(dealer_id); } }, getShopDealerId: function(shop_dealer_id, callback) { var thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.gripautobiz.php'; var dataSend = { 'type': 'dealer_id', 'shop_id': 762, 'dealer_id': shop_dealer_id }; GAEAPI.directNativeAjax(thirdPartyApi, { params: dataSend }).then(function(output) { callback(output); }); }, mobilePhone: function(mobile_phone, callback) { var mobile_phone_array = []; if (mobile_phone.length > 0) { mobile_phone_array = mobile_phone.split(","); } callback(mobile_phone_array); }, displayTelCode: function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }, branchMapLocation: function(staff_map_location_array, callback) { var lat = "0"; var lng = "0"; lat = (typeof staff_map_location_array.lat !== 'undefined' && typeof staff_map_location_array.lat !== '') ? staff_map_location_array.lat : 0;; lng = (typeof staff_map_location_array.lng !== 'undefined' && typeof staff_map_location_array.lng !== '') ? staff_map_location_array.lng : 0;; callback(lat, lng); }, linkMap: function() { var link = 'https://www.google.co.th/maps?q=' + $scope.map.positionLat + ',' + $scope.map.positionLng; window.open(link, '_blank'); }, displayDayByIndex: function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }, main: function() { var _self = this; $scope.getShopBranchIdState = _self.stateData(true, false); _self.viewRouteParams(function(dealer_id) { /* console.log('dealer_id : ', dealer_id); */ _self.getShopDealerId(dealer_id, function(output) { $scope.$apply(function() { console.log("getShopDealerId : output : ", output); $scope.dataShopDealerId = output.data; if (output.data[0].dealer_staff_data.length != 0) { _self.branchMapLocation(output.data[0].dealer_staff_data[0].staff_map_location_array[0], function(lat, lng) { $scope.map.positionLat = lat; $scope.map.positionLng = lng; }); _self.mobilePhone(output.data[0].dealer_staff_data[0].staff_mobile_phone, function(mobile_phone_array) { $scope.dataShopBranchIdMobilePhone = mobile_phone_array; }); $scope.getShopDealerIdState = _self.stateData(false, true); var myLocationTimer = setInterval(function() { window.clearInterval(myLocationTimer); $scope.googleMap().loadScript($scope.key, function() { $scope.googleMap().initMap('map', $scope.map.zoom, $scope.map.positionLat, $scope.map.positionLng, $scope.map.centerLat, $scope.map.centerLng, 'branch_info', $scope.dataShopBranchId); }); }, 500); } }); }); }); } } return dealer; }; $scope.getDealer().main(); }; return promise; });_ui_share_app.directive('componentShopDealerDetailC', function($rootScope, $routeParams) { var templateName = 'componentShopDealerDetailC'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', key: '@key', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = { name: "componentShopDealerDetailC", show: (window.location.hostname == "localhost") ? true : false }; $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getDealerId: function(params, callback) { var _self = this; var dealer_id = (params.dealer_id != undefined) ? parseInt(params.dealer_id.split("-", 1).join("")) : false; _self.consoleLog("getDealerId", "dealer_id", dealer_id); callback(dealer_id); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, directNativeAjaxApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.directNativeAjax(api, dataSend).then(function(res_api) { _self.consoleLog("directNativeAjaxApi", "res_api", res_api); state = _self.stateData(false, true); _self.consoleLog("directNativeAjaxApi", "state", state); callback(res_api, state); }); }, getIframe: function(lat, lng, callback) { var src_lat_lng = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; var callback_url = (lat != '0' && lng != '0') ? src_lat_lng : ''; callback(callback_url); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.data_api = { dealer_id: { data_send: {}, api: "extensions/devsource/dev.sugarfree/dealer/api.vono.php", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.dealer_id.data_array_state = state; _self.getDealerId(params, function(res_dealer_id) { _self.formatDataSend($scope.data_api.dealer_id, function(res_data) { var data_send = { 'type': 'dealer_id', 'shop_id': 792, 'dealer_id': res_dealer_id }; var data_params = { params: data_send }; res_data.data_send = data_params; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.directNativeAjaxApi(res_api, res_data_send, function(res_api, res_state) { res_data.data_array = res_api.data; angular.forEach(res_data.data_array, function(item, index) { _self.getIframe(item.dealer_lat, item.dealer_lng, function(res_iframe_src) { res_data.data_array[index].iframe_src = res_iframe_src; }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); }); }; return promise; });_ui_share_app.directive('componentShopDealerDetailCa', function($rootScope, $routeParams) { var templateName = 'componentShopDealerDetailCa'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', key: '@key', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = { name: "componentShopDealerDetailCa", show: (window.location.hostname == "localhost") ? true : false }; $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getDealerId: function(params, callback) { var _self = this; var dealer_id = (params.dealer_id != undefined) ? parseInt(params.dealer_id.split("-", 1).join("")) : false; _self.consoleLog("getDealerId", "dealer_id", dealer_id); callback(dealer_id); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, directNativeAjaxApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.directNativeAjax(api, dataSend).then(function(res_api) { _self.consoleLog("directNativeAjaxApi", "res_api", res_api); state = _self.stateData(false, true); _self.consoleLog("directNativeAjaxApi", "state", state); callback(res_api, state); }); }, getIframe: function(lat, lng, callback) { var src_lat_lng = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; var callback_url = (lat != '0' && lng != '0') ? src_lat_lng : ''; callback(callback_url); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.data_api = { dealer_id: { data_send: {}, api: "extensions/devsource/dev.sugarfree/dealer/api.starrynite.php", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.dealer_id.data_array_state = state; _self.getDealerId(params, function(res_dealer_id) { _self.formatDataSend($scope.data_api.dealer_id, function(res_data) { var data_send = { 'type': 'dealer_id', 'shop_id': 793, 'dealer_id': res_dealer_id }; var data_params = { params: data_send }; res_data.data_send = data_params; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.directNativeAjaxApi(res_api, res_data_send, function(res_api, res_state) { res_data.data_array = res_api.data; angular.forEach(res_data.data_array, function(item, index) { _self.getIframe(item.dealer_lat, item.dealer_lng, function(res_iframe_src) { res_data.data_array[index].iframe_src = res_iframe_src; }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); }); }; return promise; });_ui_share_app.directive('componentShopDealerDetailCb', function($rootScope, $routeParams) { var templateName = 'componentShopDealerDetailCb'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', key: '@key', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = { name: "componentShopDealerDetailCb", show: (window.location.hostname == "localhost") ? true : false }; $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getDealerId: function(params, callback) { var _self = this; var dealer_id = (params.dealer_id != undefined) ? parseInt(params.dealer_id.split("-", 1).join("")) : false; _self.consoleLog("getDealerId", "dealer_id", dealer_id); callback(dealer_id); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, directNativeAjaxApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.directNativeAjax(api, dataSend).then(function(res_api) { _self.consoleLog("directNativeAjaxApi", "res_api", res_api); state = _self.stateData(false, true); _self.consoleLog("directNativeAjaxApi", "state", state); callback(res_api, state); }); }, getIframe: function(lat, lng, callback) { var src_lat_lng = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; var callback_url = (lat != '0' && lng != '0') ? src_lat_lng : ''; callback(callback_url); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, getTel: function(number, callback) { var res_number = ""; if (number != '' && number != undefined) { if (number.indexOf("-") != -1) { var number_array = number.split("-"); var number_array_sum = number_array.join("").trim(); res_number = number_array_sum.substr(1, number_array_sum.length); } else { res_number = number.substr(1, number.length); } } res_number = "tel:+66" + res_number; callback(res_number); }, getMailto: function(email, callback) { var res_email = ""; res_email = (email != '') ? "mailto:" + email : ''; callback(res_email); }, main: function() { var _self = this; } } return getFunction; }; $scope.data_api = { dealer_id: { data_send: {}, api: "extensions/devsource/dev.sugarfree/dealer/api.slumberland.php", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.dealer_id.data_array_state = state; _self.getDealerId(params, function(res_dealer_id) { _self.formatDataSend($scope.data_api.dealer_id, function(res_data) { var data_send = { 'type': 'dealer_id', 'shop_id': 801, 'dealer_id': res_dealer_id }; var data_params = { params: data_send }; res_data.data_send = data_params; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.directNativeAjaxApi(res_api, res_data_send, function(res_api, res_state) { res_data.data_array = res_api.data; angular.forEach(res_data.data_array, function(item, index) { _self.getTel(item.dealer_phone,function(res_dealer_phone){ item.dealer_phone_url = res_dealer_phone; }); _self.getTel(item.dealer_mobile_phone,function(res_dealer_mobile_phone){ item.dealer_mobile_phone_url = res_dealer_mobile_phone; }); _self.getMailto(item.dealer_email,function(res_dealer_email){ item.dealer_email_url = res_dealer_email; }); _self.getIframe(item.dealer_lat, item.dealer_lng, function(res_iframe_src) { res_data.data_array[index].iframe_src = res_iframe_src; }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); }); }; return promise; });_ui_share_app.directive('componentShopDealerDetailD', function($rootScope, $routeParams) { var templateName = 'componentShopDealerDetailD'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', key: '@key', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = { name: "componentShopDealerDetailD", show: (window.location.hostname == "localhost") ? true : false }; $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getDealerId: function(params, callback) { var _self = this; var dealer_id = (params.dealer_id != undefined) ? parseInt(params.dealer_id.split("-", 1).join("")) : false; _self.consoleLog("getDealerId", "dealer_id", dealer_id); callback(dealer_id); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, directNativeAjaxApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.directNativeAjax(api, dataSend).then(function(res_api) { _self.consoleLog("directNativeAjaxApi", "res_api", res_api); state = _self.stateData(false, true); _self.consoleLog("directNativeAjaxApi", "state", state); callback(res_api, state); }); }, getIframe: function(lat, lng, callback) { var src_lat_lng = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; var callback_url = (lat != '0' && lng != '0') ? src_lat_lng : ''; callback(callback_url); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.data_api = { dealer_id: { data_send: {}, api: "extensions/devsource/dev.sugarfree/dealer/api.starrynite.php", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.dealer_id.data_array_state = state; _self.getDealerId(params, function(res_dealer_id) { _self.formatDataSend($scope.data_api.dealer_id, function(res_data) { var data_send = { 'type': 'dealer_id', 'shop_id': 793, 'dealer_id': res_dealer_id }; var data_params = { params: data_send }; res_data.data_send = data_params; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.directNativeAjaxApi(res_api, res_data_send, function(res_api, res_state) { res_data.data_array = res_api.data; angular.forEach(res_data.data_array, function(item, index) { _self.getIframe(item.dealer_lat, item.dealer_lng, function(res_iframe_src) { res_data.data_array[index].iframe_src = res_iframe_src; }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); }); }; return promise; }); _ui_share_app.directive('componentShopDealerDetailE', function($rootScope, $routeParams) { var templateName = 'componentShopDealerDetailE'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', key: '@key', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.map = { zoom: "14", positionLat: "0", positionLng: "0", centerLat: "0", centerLng: "0.019", innerHTML: "" }; $scope.dataShopDealerId = []; $scope.dataShopDealerIdMobilePhone = []; $scope.getShopDealerIdState = { load: true, done: false }; var w = angular.element($window); $scope.getWindowDimensions = function() { return { 'h': w.height(), 'w': w.width() }; }; w.bind('resize', function() { $scope.$apply(); }); $scope.$watch($scope.getWindowDimensions, function(newValue, oldValue) { $scope.windowHeight = newValue.h; $scope.windowWidth = newValue.w; var viewMap = ($scope.windowWidth > 991) ? $scope.map.centerLng : "0"; if ($scope.map.centerLng != viewMap) { $scope.map.centerLng = viewMap; $scope.getDealer().main(); } }, true); $scope.googleMap = function() { var map = { loadScript: function(key, callback) { var file_url = 'https://maps.googleapis.com/maps/api/js?key=' + key + '&v=3.31'; jQuery.ajax({ url: file_url, dataType: 'script', success: callback, async: true }); }, initMap: function(mapId, zoom, positionLat, positionLng, centerLat, centerLng, infoId, dataShopBranchId) { var _self = this; map = new google.maps.Map(document.getElementById(mapId), { zoom: parseFloat(zoom), center: new google.maps.LatLng(parseFloat(positionLat) - parseFloat(centerLat), parseFloat(positionLng) - parseFloat(centerLng)), mapTypeId: google.maps.MapTypeId.ROADMAP, scrollwheel: false, draggable: true, styles: [{ "featureType": "all", "elementType": "labels.text.fill", "stylers": [{ "saturation": 36 }, { "color": "#000000" }, { "lightness": 40 }] }, { "featureType": "all", "elementType": "labels.text.stroke", "stylers": [{ "visibility": "on" }, { "color": "#000000" }, { "lightness": 16 }] }, { "featureType": "all", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "administrative", "elementType": "all", "stylers": [{ "visibility": "simplified" }, { "color": "#ffcd00" }, { "saturation": "0" }, { "weight": "0.10" }] }, { "featureType": "administrative", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "administrative", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 17 }, { "weight": 1.2 }] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 20 }] }, { "featureType": "poi", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 21 }] }, { "featureType": "road.highway", "elementType": "all", "stylers": [{ "visibility": "simplified" }, { "lightness": "24" }] }, { "featureType": "road.highway", "elementType": "geometry.fill", "stylers": [{ "color": "#000000" }, { "lightness": 17 }] }, { "featureType": "road.highway", "elementType": "geometry.stroke", "stylers": [{ "color": "#000000" }, { "lightness": 29 }, { "weight": 0.2 }] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": "23" }, { "gamma": "1.08" }] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 16 }] }, { "featureType": "transit", "elementType": "geometry", "stylers": [{ "color": "#000000" }, { "lightness": 19 }] }, { "featureType": "water", "elementType": "geometry", "stylers": [{ "color": "#404547" }, { "lightness": 17 }] }] }); var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; var pin = $scope.imgPath + 'map-marker-icon-bidyang.png'; var icons = { info: { name: 'info', icon: pin } }; var features = [{ position: new google.maps.LatLng(parseFloat(positionLat), parseFloat(positionLng)), type: 'info' }]; features.forEach(function(feature) { var marker = new google.maps.Marker({ position: feature.position, icon: icons[feature.type].icon, map: map }); }); _self.innerHTML(infoId, dataShopBranchId); }, innerHTML: function(infoId, dataShopBranchId) { var info = document.getElementById(infoId); if ($scope.map.innerHTML == "") { $scope.map.innerHTML = info; } map.controls[google.maps.ControlPosition.LEFT_TOP].push($scope.map.innerHTML); } } return map; }; $scope.getDealer = function() { var dealer = { stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, viewRouteParams: function(callback) { var dealer_id = (typeof $routeParams.dealer_id !== 'undefined' && typeof $routeParams.dealer_id !== '') ? parseInt($routeParams.dealer_id) : 0; if (dealer_id != 0) { callback(dealer_id); } else { callback(dealer_id); } }, getShopDealerId: function(shop_dealer_id, callback) { var thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.php'; var dataSend = { 'type': 'dealer_id', 'shop_id': 507, 'dealer_id': shop_dealer_id }; GAEAPI.directNativeAjax(thirdPartyApi, { params: dataSend }).then(function(output) { callback(output); }); }, mobilePhone: function(mobile_phone, callback) { var mobile_phone_array = []; if (mobile_phone.length > 0) { mobile_phone_array = mobile_phone.split(","); } callback(mobile_phone_array); }, displayTelCode: function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }, branchMapLocation: function(staff_map_location_array, callback) { var lat = "0"; var lng = "0"; lat = (typeof staff_map_location_array.lat !== 'undefined' && typeof staff_map_location_array.lat !== '') ? staff_map_location_array.lat : 0;; lng = (typeof staff_map_location_array.lng !== 'undefined' && typeof staff_map_location_array.lng !== '') ? staff_map_location_array.lng : 0;; callback(lat, lng); }, linkMap: function() { var link = 'https://www.google.co.th/maps?q=' + $scope.map.positionLat + ',' + $scope.map.positionLng; window.open(link, '_blank'); }, displayDayByIndex: function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }, main: function() { var _self = this; $scope.getShopBranchIdState = _self.stateData(true, false); _self.viewRouteParams(function(dealer_id) { /* console.log('dealer_id : ', dealer_id); */ _self.getShopDealerId(dealer_id, function(output) { $scope.$apply(function() { console.log("getShopDealerId : output : ", output); $scope.dataShopDealerId = output.data; if (output.data[0].dealer_staff_data.length != 0) { _self.branchMapLocation(output.data[0].dealer_staff_data[0].staff_map_location_array[0], function(lat, lng) { $scope.map.positionLat = lat; $scope.map.positionLng = lng; }); _self.mobilePhone(output.data[0].dealer_staff_data[0].staff_mobile_phone, function(mobile_phone_array) { $scope.dataShopBranchIdMobilePhone = mobile_phone_array; }); $scope.getShopDealerIdState = _self.stateData(false, true); var myLocationTimer = setInterval(function() { window.clearInterval(myLocationTimer); $scope.googleMap().loadScript($scope.key, function() { $scope.googleMap().initMap('map', $scope.map.zoom, $scope.map.positionLat, $scope.map.positionLng, $scope.map.centerLat, $scope.map.centerLng, 'branch_info', $scope.dataShopBranchId); }); }, 500); } }); }); }); } } return dealer; }; $scope.getDealer().main(); }; return promise; }); _ui_share_app.directive('componentShopDealerListsA', function($rootScope, $routeParams, metaRender, $location) { var templateName = 'componentShopDealerListsA'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', mini: '@mini', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataPage = []; $scope.cur_page = 1; $scope.per_page = (typeof $scope.mini !== 'undefined' && typeof $scope.mini !== '') ? parseInt($scope.mini) : 10; $scope.inputSearch = (typeof $routeParams.search !== 'undefined' && typeof $routeParams.searchs !== '') ? $routeParams.search : ""; $scope.dataShopDealerLists = []; $scope.map = { latitude: 0, longitude: 0 } $scope.getShopDealerListsState = { load: true, done: false }; $scope.setPages = function(input) { var params = $routeParams; var path = { page: params.page, search: params.search, }; if (input == 'back') { if (($scope.cur_page - 1) != 0) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page - 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } else if (input == 'next') { if ($scope.cur_page < $scope.dataPage.length) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page + 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } }; $scope.search = function() { var params = $routeParams; var path = { page: params.page, search: params.search, }; // console.log("search : path : ", path); var strHref = 'dealer-lists'; strHref += '?search=' + $scope.inputSearch; $location.url(strHref).replace(); }; $scope.getDealer = function() { var dealer = { getPage: function(callback) { var params = $routeParams; $scope.cur_page = (typeof params.page !== 'undefined' && typeof params.page !== '') ? parseInt(params.page) : 1; var cur_page = $scope.cur_page; callback(cur_page); }, getSearch: function(callback) { var params = $routeParams; var search = (typeof params.search !== 'undefined' && typeof params.search !== '') ? params.search : ''; callback(search); }, stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, getShopDealerLists: function(cur_page, per_page, q, callback) { var thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.gripautobiz.php'; var dataSend = { 'type': 'dealer_lists_all', 'shop_id': 762, 'page': cur_page, 'per_page': per_page, 'q': q }; // console.log("getShopDealerLists : dataSend : ", dataSend); GAEAPI.directNativeAjax(thirdPartyApi, { params: dataSend }).then(function(output) { callback(output); }); }, getPageArray: function(dataInput, per_page) { // console.log('getPageArray : dataInput : ', dataInput); var pages = parseInt(dataInput.data.total_items) / per_page; // console.log('getPageArray : pages : ', pages); for (var i = 0; pages > i; i++) { $scope.dataPage.push(i + 1); } }, distance: function(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1 / 180; var radlat2 = Math.PI * lat2 / 180; var theta = lon1 - lon2; var radtheta = Math.PI * theta / 180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = dist * 180 / Math.PI; dist = dist * 60 * 1.1515; if (unit == "K") { dist = dist * 1.609344; } if (unit == "N") { dist = dist * 0.8684; } return dist }, getPushKg: function(callback) { var _self = this; var buildLocationArray = []; /* for (var i = 0; i < $scope.dataShopDealerLists.length; i++) { if ($scope.dataShopDealerLists[i].dealer_lat != 0 && $scope.dataShopDealerLists[i].dealer_lng != 0) { buildLocationArray.push({ dealer_email: $scope.dataShopDealerLists[i].dealer_email, dealer_firstname: $scope.dataShopDealerLists[i].dealer_firstname, dealer_id: $scope.dataShopDealerLists[i].dealer_id, dealer_image: $scope.dataShopDealerLists[i].dealer_image, dealer_lastname: $scope.dataShopDealerLists[i].dealer_lastname, dealer_lat: $scope.dataShopDealerLists[i].dealer_lat, dealer_lng: $scope.dataShopDealerLists[i].dealer_lng, dealer_mobile_phone: $scope.dataShopDealerLists[i].dealer_mobile_phone, dealer_phone: $scope.dataShopDealerLists[i].dealer_phone, dealer_title: $scope.dataShopDealerLists[i].dealer_title, dealer_kg: _self.distance($scope.map.latitude, $scope.map.longitude, $scope.dataShopDealerLists[i].dealer_lat, $scope.dataShopDealerLists[i].dealer_lng, 'K') }); } } callback(buildLocationArray); */ _self.onSearchByNearMe($scope.map.latitude, $scope.map.longitude, function(red) { /* backup */ /* red.data.dataList.length == 10 */ /* backup */ for (var i = 0; i < 10; i++) { buildLocationArray.push({ dealer_email: red.data.dataList[i].staff_email, dealer_firstname: red.data.dataList[i].staff_first_name, dealer_id: red.data.dataList[i].staff_id, dealer_image: red.data.dataList[i].staff_primary_image, dealer_lastname: red.data.dataList[i].staff_last_name, dealer_lat: 0, dealer_lng: 0, dealer_mobile_phone: red.data.dataList[i].staff_mobile_phone, dealer_phone: red.data.dataList[i].staff_phone, dealer_title: red.data.dataList[i].staff_first_name, dealer_kg: red.data.dataList[i].last_distance }); } callback(buildLocationArray); }); /* console.log("getPushKg : buildLocationArray : ", buildLocationArray); */ }, onSearchByNearMe: function(lat, lng, callback) { var dataSend = { txt_lat: lat, txt_lng: lng, txt_location_id: 0, txt_shop_id: 762 }; GAEAPI.get('dealer/lists_by_nearby', dataSend, $scope).then(function(res) { console.log("onSearchByNearMe : dataSend : ", dataSend); console.log("onSearchByNearMe : res : ", res); callback(res); }); }, getDealerListsDistance: function() { var _self = this; _self.getSearch(function(search) { _self.getShopDealerLists(1, 100, search, function(output) { $scope.$apply(function() { $scope.dataShopDealerLists = output.data.data_lists; console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); _self.getPushKg(function(buildLocationArray) { $scope.$apply(function() { $scope.dataShopDealerLists = buildLocationArray; $scope.getShopDealerListsState = _self.stateData(false, true); }); }); }); }) }); }, getLocation: function() { var _self = this; $scope.dataPage = []; $scope.getShopDealerListsState = _self.stateData(true, false); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $scope.$apply(function() { // console.log("getLocation : position : ", position); $scope.map.latitude = position.coords.latitude; // console.log("getLocation : position : latitude : ", position.coords.latitude); $scope.map.longitude = position.coords.longitude; // console.log("getLocation : position : longitude : ", position.coords.longitude); _self.getDealerListsDistance(); }); }); } else { alert(" Geolocation is not supported by this browser. "); } }, main: function() { var _self = this; $scope.getShopDealerListsState = _self.stateData(true, false); _self.getPage(function(cur_page) { _self.getSearch(function(search) { if (search != '') { _self.getShopDealerLists(cur_page, $scope.per_page, search, function(output) { $scope.$apply(function() { _self.getPageArray(output, $scope.per_page); // console.log("getShopDealerLists : output : ", output); $scope.dataShopDealerLists = output.data.data_lists; // console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); $scope.getShopDealerListsState = _self.stateData(false, true); }); }); } else { _self.getLocation(); } }); }); } } return dealer; }; $scope.getDealer().main(); }; return promise; });_ui_share_app.directive('componentShopDealerListsB', function($rootScope, $routeParams, $location) { var templateName = 'componentShopDealerListsB'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', mini: '@mini', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataPage = []; $scope.cur_page = 1; $scope.per_page = (typeof $scope.mini !== 'undefined' && typeof $scope.mini !== '') ? parseInt($scope.mini) : 10; $scope.inputSearch = (typeof $routeParams.search !== 'undefined' && typeof $routeParams.searchs !== '') ? $routeParams.search : ""; $scope.dataShopDealerLists = []; $scope.map = { latitude: 0, longitude: 0 } $scope.getShopDealerListsState = { load: true, done: false }; $scope.setPages = function(input) { var params = $routeParams; var path = { page: params.page, search: params.search, }; if (input == 'back') { if (($scope.cur_page - 1) != 0) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page - 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } else if (input == 'next') { if ($scope.cur_page < $scope.dataPage.length) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page + 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } }; $scope.search = function() { var params = $routeParams; var path = { page: params.page, search: params.search, }; // console.log("search : path : ", path); var strHref = 'dealer-lists'; strHref += '?search=' + $scope.inputSearch; $location.url(strHref).replace(); }; $scope.getDealer = function() { var dealer = { linkMap: function(positionLat, positionLng) { var link = 'https://www.google.co.th/maps?q=' + positionLat + ',' + positionLng; window.open(link, '_blank'); }, getPage: function(callback) { var params = $routeParams; $scope.cur_page = (typeof params.page !== 'undefined' && typeof params.page !== '') ? parseInt(params.page) : 1; var cur_page = $scope.cur_page; callback(cur_page); }, getSearch: function(callback) { var params = $routeParams; var search = (typeof params.search !== 'undefined' && typeof params.search !== '') ? params.search : ''; callback(search); }, stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, getShopDealerLists: function(cur_page, per_page, q, callback) { var thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.infosat.php'; var dataSend = { 'type': 'dealer_lists_all', 'shop_id': 754, 'page': cur_page, 'per_page': per_page, 'q': q }; // console.log("getShopDealerLists : dataSend : ", dataSend); GAEAPI.directNativeAjax(thirdPartyApi, { params: dataSend }).then(function(output) { callback(output); }); }, getPageArray: function(dataInput, per_page) { // console.log('getPageArray : dataInput : ', dataInput); var pages = parseInt(dataInput.data.total_items) / per_page; // console.log('getPageArray : pages : ', pages); for (var i = 0; pages > i; i++) { $scope.dataPage.push(i + 1); } }, distance: function(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1 / 180; var radlat2 = Math.PI * lat2 / 180; var theta = lon1 - lon2; var radtheta = Math.PI * theta / 180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = dist * 180 / Math.PI; dist = dist * 60 * 1.1515; if (unit == "K") { dist = dist * 1.609344; } if (unit == "N") { dist = dist * 0.8684; } return dist }, getPushKg: function(callback) { var _self = this; var buildLocationArray = []; for (var i = 0; i < $scope.dataShopDealerLists.length; i++) { if ($scope.dataShopDealerLists[i].dealer_lat != 0 && $scope.dataShopDealerLists[i].dealer_lng != 0) { buildLocationArray.push({ dealer_email: $scope.dataShopDealerLists[i].dealer_email, dealer_firstname: $scope.dataShopDealerLists[i].dealer_firstname, dealer_id: $scope.dataShopDealerLists[i].dealer_id, dealer_image: $scope.dataShopDealerLists[i].dealer_image, dealer_lastname: $scope.dataShopDealerLists[i].dealer_lastname, dealer_lat: $scope.dataShopDealerLists[i].dealer_lat, dealer_lng: $scope.dataShopDealerLists[i].dealer_lng, dealer_mobile_phone: $scope.dataShopDealerLists[i].dealer_mobile_phone, dealer_phone: $scope.dataShopDealerLists[i].dealer_phone, dealer_title: $scope.dataShopDealerLists[i].dealer_title, dealer_kg: _self.distance($scope.map.latitude, $scope.map.longitude, $scope.dataShopDealerLists[i].dealer_lat, $scope.dataShopDealerLists[i].dealer_lng, 'K') }); } } // console.log("getPushKg : buildLocationArray : ", buildLocationArray); callback(buildLocationArray); }, getDealerListsDistance: function() { var _self = this; _self.getSearch(function(search) { _self.getShopDealerLists(1, 100, search, function(output) { $scope.$apply(function() { $scope.dataShopDealerLists = output.data.data_lists; // console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); _self.getPushKg(function(buildLocationArray) { $scope.dataShopDealerLists = buildLocationArray; $scope.getShopDealerListsState = _self.stateData(false, true); }); }); }) }); }, displayTelCode: function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }, getLocation: function() { var _self = this; $scope.dataPage = []; $scope.getShopDealerListsState = _self.stateData(true, false); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $scope.$apply(function() { // console.log("getLocation : position : ", position); $scope.map.latitude = position.coords.latitude; // console.log("getLocation : position : latitude : ", position.coords.latitude); $scope.map.longitude = position.coords.longitude; // console.log("getLocation : position : longitude : ", position.coords.longitude); _self.getDealerListsDistance(); }); }); } else { alert(" Geolocation is not supported by this browser. "); } }, main: function() { var _self = this; $scope.getShopDealerListsState = _self.stateData(true, false); _self.getPage(function(cur_page) { _self.getSearch(function(search) { _self.getShopDealerLists(cur_page, $scope.per_page, search, function(output) { $scope.$apply(function() { _self.getPageArray(output, $scope.per_page); // console.log("getShopDealerLists : output : ", output); $scope.dataShopDealerLists = output.data.data_lists; // console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); $scope.getShopDealerListsState = _self.stateData(false, true); }); }) }); }); } } return dealer; }; $scope.getDealer().main(); }; return promise; });_ui_share_app.directive('componentShopDealerListsC', function($rootScope, $routeParams, metaRender, $location) { var templateName = 'componentShopDealerListsC'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', mini: '@mini', language: '@language', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataPage = []; $scope.cur_page = 1; $scope.per_page = (typeof $scope.mini !== 'undefined' && typeof $scope.mini !== '') ? parseInt($scope.mini) : 10; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; $scope.inputSearch = (typeof $routeParams.search !== 'undefined' && typeof $routeParams.searchs !== '') ? $routeParams.search : ""; $scope.dataShopDealerLists = []; $scope.map = { latitude: 0, longitude: 0 } $scope.getShopDealerListsState = { load: true, done: false }; $scope.getPages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id; _self.locationUrlReplace(page); } } return getFunction; }; $scope.setPages = function(input) { var params = $routeParams; var path = { page: params.page, search: params.search, }; if (input == 'back') { if (($scope.cur_page - 1) != 0) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page - 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } else if (input == 'next') { if ($scope.cur_page < $scope.dataPage.length) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page + 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } }; $scope.search = function() { var params = $routeParams; var path = { page: params.page, search: params.search, }; // console.log("search : path : ", path); var strHref = 'dealer-lists'; strHref += '?search=' + $scope.inputSearch; $location.url(strHref).replace(); }; $scope.getDealer = function() { var dealer = { linkMap: function(positionLat, positionLng) { var link = 'https://www.google.co.th/maps?q=' + positionLat + ',' + positionLng; window.open(link, '_blank'); }, getPage: function(callback) { var params = $routeParams; $scope.cur_page = (typeof params.page !== 'undefined' && typeof params.page !== '') ? parseInt(params.page) : 1; var cur_page = $scope.cur_page; callback(cur_page); }, getSearch: function(callback) { var params = $routeParams; var search = (typeof params.search !== 'undefined' && typeof params.search !== '') ? params.search : ''; callback(search); }, stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, getShopDealerLists: function(cur_page, per_page, q, callback) { var thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.vono.php'; var dataSend = { 'type': 'dealer_lists_all', 'shop_id': 792, 'page': cur_page, 'per_page': per_page, 'q': q }; // console.log("getShopDealerLists : dataSend : ", dataSend); GAEAPI.directNativeAjax(thirdPartyApi, { params: dataSend }).then(function(output) { callback(output); }); }, getPageArray: function(dataInput, per_page) { // console.log('getPageArray : dataInput : ', dataInput); var pages = parseInt(dataInput.data.total_items) / per_page; // console.log('getPageArray : pages : ', pages); for (var i = 0; pages > i; i++) { $scope.dataPage.push(i + 1); } }, distance: function(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1 / 180; var radlat2 = Math.PI * lat2 / 180; var theta = lon1 - lon2; var radtheta = Math.PI * theta / 180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = dist * 180 / Math.PI; dist = dist * 60 * 1.1515; if (unit == "K") { dist = dist * 1.609344; } if (unit == "N") { dist = dist * 0.8684; } return dist }, getPushKg: function(callback) { var _self = this; var buildLocationArray = []; for (var i = 0; i < $scope.dataShopDealerLists.length; i++) { if ($scope.dataShopDealerLists[i].dealer_lat != 0 && $scope.dataShopDealerLists[i].dealer_lng != 0) { buildLocationArray.push({ dealer_email: $scope.dataShopDealerLists[i].dealer_email, dealer_firstname: $scope.dataShopDealerLists[i].dealer_firstname, dealer_id: $scope.dataShopDealerLists[i].dealer_id, dealer_image: $scope.dataShopDealerLists[i].dealer_image, dealer_lastname: $scope.dataShopDealerLists[i].dealer_lastname, dealer_lat: $scope.dataShopDealerLists[i].dealer_lat, dealer_lng: $scope.dataShopDealerLists[i].dealer_lng, dealer_mobile_phone: $scope.dataShopDealerLists[i].dealer_mobile_phone, dealer_phone: $scope.dataShopDealerLists[i].dealer_phone, dealer_title: $scope.dataShopDealerLists[i].dealer_title, dealer_kg: _self.distance($scope.map.latitude, $scope.map.longitude, $scope.dataShopDealerLists[i].dealer_lat, $scope.dataShopDealerLists[i].dealer_lng, 'K') }); } } // console.log("getPushKg : buildLocationArray : ", buildLocationArray); callback(buildLocationArray); }, getDealerListsDistance: function() { var _self = this; _self.getSearch(function(search) { _self.getShopDealerLists(1, 100, search, function(output) { $scope.$apply(function() { $scope.dataShopDealerLists = output.data.data_lists; console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); _self.getPushKg(function(buildLocationArray) { $scope.dataShopDealerLists = buildLocationArray; $scope.getShopDealerListsState = _self.stateData(false, true); }); }); }) }); }, displayTelCode: function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }, getLocation: function() { var _self = this; $scope.dataPage = []; $scope.getShopDealerListsState = _self.stateData(true, false); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $scope.$apply(function() { // console.log("getLocation : position : ", position); $scope.map.latitude = position.coords.latitude; // console.log("getLocation : position : latitude : ", position.coords.latitude); $scope.map.longitude = position.coords.longitude; // console.log("getLocation : position : longitude : ", position.coords.longitude); _self.getDealerListsDistance(); }); }); } else { alert(" Geolocation is not supported by this browser. "); } }, getTel: function(number, callback) { var res_number = ""; if (number != '' && number != undefined) { if (number.indexOf("-") != -1) { var number_array = number.split("-"); var number_array_sum = number_array.join("").trim(); res_number = number_array_sum.substr(1, number_array_sum.length); } else { res_number = number.substr(1, number.length); } } res_number = "tel:+66" + res_number; callback(res_number); }, getMailto: function(email, callback) { var res_email = ""; res_email = (email != '') ? "mailto:" + email : ''; callback(res_email); }, main: function() { var _self = this; $scope.getShopDealerListsState = _self.stateData(true, false); _self.getPage(function(cur_page) { _self.getSearch(function(search) { _self.getShopDealerLists(cur_page, $scope.per_page, search, function(output) { $scope.$apply(function() { _self.getPageArray(output, $scope.per_page); console.log("getShopDealerLists : output : ", output); angular.forEach(output.data.data_lists, function(item, index) { _self.getTel(item.dealer_mobile_phone,function(res_dealer_mobile_phone){ item.dealer_mobile_phone_url = res_dealer_mobile_phone; }); _self.getMailto(item.dealer_email,function(res_dealer_email){ item.dealer_email_url = res_dealer_email; }); $scope.dataShopDealerLists.push(item) }); console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); $scope.getShopDealerListsState = _self.stateData(false, true); }); }) }); }); } } return dealer; }; $scope.getDealer().main(); }; return promise; });_ui_share_app.directive('componentShopDealerListsCa', function($rootScope, $routeParams, metaRender, $location) { var templateName = 'componentShopDealerListsCa'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', mini: '@mini', language: '@language', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataPage = []; $scope.cur_page = 1; $scope.per_page = (typeof $scope.mini !== 'undefined' && typeof $scope.mini !== '') ? parseInt($scope.mini) : 10; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; $scope.inputSearch = (typeof $routeParams.search !== 'undefined' && typeof $routeParams.searchs !== '') ? $routeParams.search : ""; $scope.dataShopDealerLists = []; $scope.map = { latitude: 0, longitude: 0 } $scope.getShopDealerListsState = { load: true, done: false }; $scope.getPages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id; _self.locationUrlReplace(page); } } return getFunction; }; $scope.setPages = function(input) { var params = $routeParams; var path = { page: params.page, search: params.search, }; if (input == 'back') { if (($scope.cur_page - 1) != 0) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page - 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } else if (input == 'next') { if ($scope.cur_page < $scope.dataPage.length) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page + 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } }; $scope.search = function() { var params = $routeParams; var path = { page: params.page, search: params.search, }; // console.log("search : path : ", path); var strHref = 'dealer-lists'; strHref += '?search=' + $scope.inputSearch; $location.url(strHref).replace(); }; $scope.getDealer = function() { var dealer = { linkMap: function(positionLat, positionLng) { var link = 'https://www.google.co.th/maps?q=' + positionLat + ',' + positionLng; window.open(link, '_blank'); }, getPage: function(callback) { var params = $routeParams; $scope.cur_page = (typeof params.page !== 'undefined' && typeof params.page !== '') ? parseInt(params.page) : 1; var cur_page = $scope.cur_page; callback(cur_page); }, getSearch: function(callback) { var params = $routeParams; var search = (typeof params.search !== 'undefined' && typeof params.search !== '') ? params.search : ''; callback(search); }, stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, getShopDealerLists: function(cur_page, per_page, q, callback) { var thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.starrynite.php'; var dataSend = { 'type': 'dealer_lists_all', 'shop_id': 793, 'page': cur_page, 'per_page': per_page, 'q': q }; // console.log("getShopDealerLists : dataSend : ", dataSend); GAEAPI.directNativeAjax(thirdPartyApi, { params: dataSend }).then(function(output) { callback(output); }); }, getPageArray: function(dataInput, per_page) { // console.log('getPageArray : dataInput : ', dataInput); var pages = parseInt(dataInput.data.total_items) / per_page; // console.log('getPageArray : pages : ', pages); for (var i = 0; pages > i; i++) { $scope.dataPage.push(i + 1); } }, distance: function(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1 / 180; var radlat2 = Math.PI * lat2 / 180; var theta = lon1 - lon2; var radtheta = Math.PI * theta / 180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = dist * 180 / Math.PI; dist = dist * 60 * 1.1515; if (unit == "K") { dist = dist * 1.609344; } if (unit == "N") { dist = dist * 0.8684; } return dist }, getPushKg: function(callback) { var _self = this; var buildLocationArray = []; for (var i = 0; i < $scope.dataShopDealerLists.length; i++) { if ($scope.dataShopDealerLists[i].dealer_lat != 0 && $scope.dataShopDealerLists[i].dealer_lng != 0) { buildLocationArray.push({ dealer_email: $scope.dataShopDealerLists[i].dealer_email, dealer_firstname: $scope.dataShopDealerLists[i].dealer_firstname, dealer_id: $scope.dataShopDealerLists[i].dealer_id, dealer_image: $scope.dataShopDealerLists[i].dealer_image, dealer_lastname: $scope.dataShopDealerLists[i].dealer_lastname, dealer_lat: $scope.dataShopDealerLists[i].dealer_lat, dealer_lng: $scope.dataShopDealerLists[i].dealer_lng, dealer_mobile_phone: $scope.dataShopDealerLists[i].dealer_mobile_phone, dealer_phone: $scope.dataShopDealerLists[i].dealer_phone, dealer_title: $scope.dataShopDealerLists[i].dealer_title, dealer_kg: _self.distance($scope.map.latitude, $scope.map.longitude, $scope.dataShopDealerLists[i].dealer_lat, $scope.dataShopDealerLists[i].dealer_lng, 'K') }); } } // console.log("getPushKg : buildLocationArray : ", buildLocationArray); callback(buildLocationArray); }, getDealerListsDistance: function() { var _self = this; _self.getSearch(function(search) { _self.getShopDealerLists(1, 100, search, function(output) { $scope.$apply(function() { $scope.dataShopDealerLists = output.data.data_lists; console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); _self.getPushKg(function(buildLocationArray) { $scope.dataShopDealerLists = buildLocationArray; $scope.getShopDealerListsState = _self.stateData(false, true); }); }); }) }); }, displayTelCode: function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }, getLocation: function() { var _self = this; $scope.dataPage = []; $scope.getShopDealerListsState = _self.stateData(true, false); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $scope.$apply(function() { // console.log("getLocation : position : ", position); $scope.map.latitude = position.coords.latitude; // console.log("getLocation : position : latitude : ", position.coords.latitude); $scope.map.longitude = position.coords.longitude; // console.log("getLocation : position : longitude : ", position.coords.longitude); _self.getDealerListsDistance(); }); }); } else { alert(" Geolocation is not supported by this browser. "); } }, getTel: function(number, callback) { var res_number = ""; if (number != '' && number != undefined) { if (number.indexOf("-") != -1) { var number_array = number.split("-"); var number_array_sum = number_array.join("").trim(); res_number = number_array_sum.substr(1, number_array_sum.length); } else { res_number = number.substr(1, number.length); } } res_number = "tel:+66" + res_number; callback(res_number); }, getMailto: function(email, callback) { var res_email = ""; res_email = (email != '') ? "mailto:" + email : ''; callback(res_email); }, main: function() { var _self = this; $scope.getShopDealerListsState = _self.stateData(true, false); _self.getPage(function(cur_page) { _self.getSearch(function(search) { _self.getShopDealerLists(cur_page, $scope.per_page, search, function(output) { $scope.$apply(function() { _self.getPageArray(output, $scope.per_page); console.log("getShopDealerLists : output : ", output); angular.forEach(output.data.data_lists, function(item, index) { _self.getTel(item.dealer_mobile_phone, function(res_dealer_mobile_phone) { item.dealer_mobile_phone_url = res_dealer_mobile_phone; }); _self.getMailto(item.dealer_email, function(res_dealer_email) { item.dealer_email_url = res_dealer_email; }); $scope.dataShopDealerLists.push(item) }); console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); $scope.getShopDealerListsState = _self.stateData(false, true); }); }) }); }); } } return dealer; }; $scope.getDealer().main(); }; return promise; });_ui_share_app.directive('componentShopDealerListsCb', function($rootScope, $routeParams, metaRender, $location) { var templateName = 'componentShopDealerListsCb'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', mini: '@mini', language: '@language', navigationhover: '@navigationhover', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataPage = []; $scope.cur_page = 1; $scope.per_page = (typeof $scope.mini !== 'undefined' && typeof $scope.mini !== '') ? parseInt($scope.mini) : 10; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; $scope.inputSearch = (typeof $routeParams.search !== 'undefined' && typeof $routeParams.searchs !== '') ? $routeParams.search : ""; $scope._navigationhover = ($scope.navigationhover != undefined && $scope.navigationhover != "") ? $scope.navigationhover : "primary"; $scope.dataShopDealerLists = []; $scope.map = { latitude: 0, longitude: 0 } $scope.getShopDealerListsState = { load: true, done: false }; $scope.getPages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id; _self.locationUrlReplace(page); } } return getFunction; }; $scope.setPages = function(input) { var params = $routeParams; var path = { page: params.page, search: params.search, }; if (input == 'back') { if (($scope.cur_page - 1) != 0) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page - 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } else if (input == 'next') { if ($scope.cur_page < $scope.dataPage.length) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page + 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } }; $scope.search = function() { var params = $routeParams; var path = { page: params.page, search: params.search, }; // console.log("search : path : ", path); var strHref = 'dealer-lists'; strHref += '?search=' + $scope.inputSearch; $location.url(strHref).replace(); }; $scope.getDealer = function() { var dealer = { linkMap: function(positionLat, positionLng) { var link = 'https://www.google.co.th/maps?q=' + positionLat + ',' + positionLng; window.open(link, '_blank'); }, getPage: function(callback) { var params = $routeParams; $scope.cur_page = (typeof params.page !== 'undefined' && typeof params.page !== '') ? parseInt(params.page) : 1; var cur_page = $scope.cur_page; callback(cur_page); }, getSearch: function(callback) { var params = $routeParams; var search = (typeof params.search !== 'undefined' && typeof params.search !== '') ? params.search : ''; callback(search); }, stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, getShopDealerLists: function(cur_page, per_page, q, callback) { var thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.slumberland.php'; var dataSend = { 'type': 'dealer_lists_all', 'shop_id': 801, 'page': cur_page, 'per_page': per_page, 'q': q }; // console.log("getShopDealerLists : dataSend : ", dataSend); GAEAPI.directNativeAjax(thirdPartyApi, { params: dataSend }).then(function(output) { callback(output); }); }, getPageArray: function(dataInput, per_page) { // console.log('getPageArray : dataInput : ', dataInput); var pages = parseInt(dataInput.data.total_items) / per_page; // console.log('getPageArray : pages : ', pages); for (var i = 0; pages > i; i++) { $scope.dataPage.push(i + 1); } }, distance: function(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1 / 180; var radlat2 = Math.PI * lat2 / 180; var theta = lon1 - lon2; var radtheta = Math.PI * theta / 180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = dist * 180 / Math.PI; dist = dist * 60 * 1.1515; if (unit == "K") { dist = dist * 1.609344; } if (unit == "N") { dist = dist * 0.8684; } return dist }, getPushKg: function(callback) { var _self = this; var buildLocationArray = []; for (var i = 0; i < $scope.dataShopDealerLists.length; i++) { if ($scope.dataShopDealerLists[i].dealer_lat != 0 && $scope.dataShopDealerLists[i].dealer_lng != 0) { buildLocationArray.push({ dealer_email: $scope.dataShopDealerLists[i].dealer_email, dealer_firstname: $scope.dataShopDealerLists[i].dealer_firstname, dealer_id: $scope.dataShopDealerLists[i].dealer_id, dealer_image: $scope.dataShopDealerLists[i].dealer_image, dealer_lastname: $scope.dataShopDealerLists[i].dealer_lastname, dealer_lat: $scope.dataShopDealerLists[i].dealer_lat, dealer_lng: $scope.dataShopDealerLists[i].dealer_lng, dealer_mobile_phone: $scope.dataShopDealerLists[i].dealer_mobile_phone, dealer_phone: $scope.dataShopDealerLists[i].dealer_phone, dealer_title: $scope.dataShopDealerLists[i].dealer_title, dealer_kg: _self.distance($scope.map.latitude, $scope.map.longitude, $scope.dataShopDealerLists[i].dealer_lat, $scope.dataShopDealerLists[i].dealer_lng, 'K') }); } } // console.log("getPushKg : buildLocationArray : ", buildLocationArray); callback(buildLocationArray); }, getDealerListsDistance: function() { var _self = this; _self.getSearch(function(search) { _self.getShopDealerLists(1, 100, search, function(output) { $scope.$apply(function() { $scope.dataShopDealerLists = output.data.data_lists; console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); _self.getPushKg(function(buildLocationArray) { $scope.dataShopDealerLists = buildLocationArray; $scope.getShopDealerListsState = _self.stateData(false, true); }); }); }) }); }, displayTelCode: function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }, getLocation: function() { var _self = this; $scope.dataPage = []; $scope.getShopDealerListsState = _self.stateData(true, false); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $scope.$apply(function() { // console.log("getLocation : position : ", position); $scope.map.latitude = position.coords.latitude; // console.log("getLocation : position : latitude : ", position.coords.latitude); $scope.map.longitude = position.coords.longitude; // console.log("getLocation : position : longitude : ", position.coords.longitude); _self.getDealerListsDistance(); }); }); } else { alert(" Geolocation is not supported by this browser. "); } }, getTel: function(number, callback) { var res_number = ""; if (number != '' && number != undefined) { if (number.indexOf("-") != -1) { var number_array = number.split("-"); var number_array_sum = number_array.join("").trim(); res_number = number_array_sum.substr(1, number_array_sum.length); } else { res_number = number.substr(1, number.length); } } res_number = "tel:+66" + res_number; callback(res_number); }, getMailto: function(email, callback) { var res_email = ""; res_email = (email != '') ? "mailto:" + email : ''; callback(res_email); }, main: function() { var _self = this; $scope.getShopDealerListsState = _self.stateData(true, false); _self.getPage(function(cur_page) { _self.getSearch(function(search) { _self.getShopDealerLists(cur_page, $scope.per_page, search, function(output) { $scope.$apply(function() { _self.getPageArray(output, $scope.per_page); console.log("getShopDealerLists : output : ", output); angular.forEach(output.data.data_lists, function(item, index) { _self.getTel(item.dealer_phone,function(res_dealer_phone){ item.dealer_phone_url = res_dealer_phone; }); _self.getTel(item.dealer_mobile_phone,function(res_dealer_mobile_phone){ item.dealer_mobile_phone_url = res_dealer_mobile_phone; }); _self.getMailto(item.dealer_email,function(res_dealer_email){ item.dealer_email_url = res_dealer_email; }); $scope.dataShopDealerLists.push(item) }); console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); $scope.getShopDealerListsState = _self.stateData(false, true); }); }) }); }); } } return dealer; }; $scope.getDealer().main(); }; return promise; });_ui_share_app.directive('componentShopDealerListsD', function($rootScope, $routeParams, metaRender, $location) { var templateName = 'componentShopDealerListsD'; var componentMain = 'componentShopDealer'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', mini: '@mini', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataPage = []; $scope.cur_page = 1; $scope.per_page = (typeof $scope.mini !== 'undefined' && typeof $scope.mini !== '') ? parseInt($scope.mini) : 10; $scope.inputSearch = (typeof $routeParams.search !== 'undefined' && typeof $routeParams.searchs !== '') ? $routeParams.search : ""; $scope.dataShopDealerLists = []; $scope.map = { latitude: 0, longitude: 0 } $scope.getShopDealerListsState = { load: true, done: false }; $scope.getPages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id; _self.locationUrlReplace(page); } } return getFunction; }; $scope.setPages = function(input) { var params = $routeParams; var path = { page: params.page, search: params.search, }; if (input == 'back') { if (($scope.cur_page - 1) != 0) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page - 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } else if (input == 'next') { if ($scope.cur_page < $scope.dataPage.length) { var strHref = 'dealer-lists'; strHref += '?page=' + ($scope.cur_page + 1); strHref += '&search=' + $scope.inputSearch; strHref += '&base_shop_name=gripautobiz'; $location.url(strHref).replace(); } } }; $scope.search = function() { var params = $routeParams; var path = { page: params.page, search: params.search, }; // console.log("search : path : ", path); var strHref = 'dealer-lists'; strHref += '?search=' + $scope.inputSearch; $location.url(strHref).replace(); }; $scope.getDealer = function() { var dealer = { linkMap: function(positionLat, positionLng) { var link = 'https://www.google.co.th/maps?q=' + positionLat + ',' + positionLng; window.open(link, '_blank'); }, getPage: function(callback) { var params = $routeParams; $scope.cur_page = (typeof params.page !== 'undefined' && typeof params.page !== '') ? parseInt(params.page) : 1; var cur_page = $scope.cur_page; callback(cur_page); }, getSearch: function(callback) { var params = $routeParams; var search = (typeof params.search !== 'undefined' && typeof params.search !== '') ? params.search : ''; callback(search); }, stateData: function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }, getShopDealerLists: function(cur_page, per_page, q, callback) { var thirdPartyApi = 'extensions/devsource/dev.sugarfree/dealer/api.starrynite.php'; var dataSend = { 'type': 'dealer_lists_all', 'shop_id': 793, 'page': cur_page, 'per_page': per_page, 'q': q }; // console.log("getShopDealerLists : dataSend : ", dataSend); GAEAPI.directNativeAjax(thirdPartyApi, { params: dataSend }).then(function(output) { callback(output); }); }, getPageArray: function(dataInput, per_page) { // console.log('getPageArray : dataInput : ', dataInput); var pages = parseInt(dataInput.data.total_items) / per_page; // console.log('getPageArray : pages : ', pages); for (var i = 0; pages > i; i++) { $scope.dataPage.push(i + 1); } }, distance: function(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1 / 180; var radlat2 = Math.PI * lat2 / 180; var theta = lon1 - lon2; var radtheta = Math.PI * theta / 180; var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist); dist = dist * 180 / Math.PI; dist = dist * 60 * 1.1515; if (unit == "K") { dist = dist * 1.609344; } if (unit == "N") { dist = dist * 0.8684; } return dist }, getPushKg: function(callback) { var _self = this; var buildLocationArray = []; for (var i = 0; i < $scope.dataShopDealerLists.length; i++) { if ($scope.dataShopDealerLists[i].dealer_lat != 0 && $scope.dataShopDealerLists[i].dealer_lng != 0) { buildLocationArray.push({ dealer_email: $scope.dataShopDealerLists[i].dealer_email, dealer_firstname: $scope.dataShopDealerLists[i].dealer_firstname, dealer_id: $scope.dataShopDealerLists[i].dealer_id, dealer_image: $scope.dataShopDealerLists[i].dealer_image, dealer_lastname: $scope.dataShopDealerLists[i].dealer_lastname, dealer_lat: $scope.dataShopDealerLists[i].dealer_lat, dealer_lng: $scope.dataShopDealerLists[i].dealer_lng, dealer_mobile_phone: $scope.dataShopDealerLists[i].dealer_mobile_phone, dealer_phone: $scope.dataShopDealerLists[i].dealer_phone, dealer_title: $scope.dataShopDealerLists[i].dealer_title, dealer_kg: _self.distance($scope.map.latitude, $scope.map.longitude, $scope.dataShopDealerLists[i].dealer_lat, $scope.dataShopDealerLists[i].dealer_lng, 'K') }); } } // console.log("getPushKg : buildLocationArray : ", buildLocationArray); callback(buildLocationArray); }, getDealerListsDistance: function() { var _self = this; _self.getSearch(function(search) { _self.getShopDealerLists(1, 100, search, function(output) { $scope.$apply(function() { $scope.dataShopDealerLists = output.data.data_lists; console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); _self.getPushKg(function(buildLocationArray) { $scope.dataShopDealerLists = buildLocationArray; $scope.getShopDealerListsState = _self.stateData(false, true); }); }); }) }); }, displayTelCode: function(telString) { if (telString != 'undefined') { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } else { return 0; } }, getLocation: function() { var _self = this; $scope.dataPage = []; $scope.getShopDealerListsState = _self.stateData(true, false); if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { $scope.$apply(function() { // console.log("getLocation : position : ", position); $scope.map.latitude = position.coords.latitude; // console.log("getLocation : position : latitude : ", position.coords.latitude); $scope.map.longitude = position.coords.longitude; // console.log("getLocation : position : longitude : ", position.coords.longitude); _self.getDealerListsDistance(); }); }); } else { alert(" Geolocation is not supported by this browser. "); } }, main: function() { var _self = this; $scope.getShopDealerListsState = _self.stateData(true, false); _self.getPage(function(cur_page) { _self.getSearch(function(search) { _self.getShopDealerLists(cur_page, $scope.per_page, search, function(output) { $scope.$apply(function() { _self.getPageArray(output, $scope.per_page); console.log("getShopDealerLists : output : ", output); $scope.dataShopDealerLists = output.data.data_lists; console.log("getShopDealerLists : dataShopDealerLists : ", $scope.dataShopDealerLists); $scope.getShopDealerListsState = _self.stateData(false, true); }); }) }); }); } } return dealer; }; $scope.getDealer().main(); }; return promise; });_ui_share_app.factory('$componentShopLocator', function componentShopLocator($routeParams, $timeout) { return });_ui_share_app.directive('componentShopLocatorA', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorA'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', color_: '@color', color_hover: '@colorhover', color_active: '@coloractive', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data = []; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.branchListState = { load: true, done: false }; $scope.branchList = []; $scope.getBranchList = function() { $scope.branchListState = { load: true, done: false }; var dataSend = { 'cur_page': 1, 'per_page': 100 }; GAEAPI.get('shop_branch/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branchList = res.data.dataList; } $scope.branchListState = { load: false, done: true }; }); } $scope.getBranchList(); $scope.makeDummy = function() { var o = function(i) { return { 'branch_id': i, 'branch_name': 'บริษัท เอ็กซ์-สปีด กรุ๊ป จำกัด', 'branch_phone': '02-979-5965-66', 'branch_mobile': '087-9999653', 'branch_description': 'สำนักงานใหญ่ detail', 'branch_short_description': 'สำนักงานใหญ่', 'branch_location_title': 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000', 'branch_location_latitude': '0', 'branch_location_longtitude': '0', 'branch_workingtime_array': [{ 'txt_index': 1, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, { 'txt_index': 2, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 3, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 4, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 5, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 6, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 7, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, ], 'branch_image': [{ 'image_url': 'https://image.getappeasy.com/src/images/2000/1032/0033/32033t1496650984.jpg' }] }; } var r = [o(1)]; return r; }; if ($scope.data.length <= 0) { $scope.getData(); } $scope.displayDayByIndex = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.mapQueryString = function() { var a = 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000'; var b = 'https://www.google.co.th/maps?q=' + a.split(' ').join('+') + '&output=embed'; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildLinkPhoneByTxt = function(str) {}; $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentShopLocatorB', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorB'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', color_: '@color', color_hover: '@colorhover', color_active: '@coloractive', placeholderimage: '@placeholderimage', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data = []; $scope.branch = []; $scope.showPlaceHolderImage = ($scope.placeholderimage!='' && $scope.placeholderimage!=undefined) ? true : false; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.branchListState = { load: true, done: false, load_more: false }; $scope.branchList = []; $scope.fetchTimes = 1; $scope.data_per_page = 12; $scope.maxresult = 4; $scope.getBranchList = function(cpage, ppage) { $scope.branchListState = { load: true, done: false, load_more: false }; var dataSend = { 'cur_page': cpage, 'per_page': ppage }; GAEAPI.get('shop_branch/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branch = res.data; $scope.branchList = res.data.dataList; } $scope.branchListState = { load: false, done: true, load_more: false }; }); } $scope.getBranchList($scope.fetchTimes, $scope.data_per_page); $scope.getBranchListLoadMore = function(cpage, ppage) { $scope.branchListState = { load: false, done: false, load_more: true }; var dataSend = { 'cur_page': cpage, 'per_page': ppage }; GAEAPI.get('shop_branch/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branch = res.data; $scope.branchList = res.data.dataList; } $scope.branchListState = { load: false, done: false, load_more: false }; }); } $scope.loadMore = function() { $scope.data_per_page = parseInt($scope.data_per_page) + parseInt($scope.maxresult); $scope.getBranchListLoadMore($scope.fetchTimes, $scope.data_per_page); }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentShopLocatorC', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorC'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', color_: '@color', color_hover: '@colorhover', color_active: '@coloractive', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data = []; $scope.branch = []; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.branchListState = { load: true, done: false, load_more: false }; $scope.branchList = []; $scope.fetchTimes = 1; $scope.data_per_page = 12; $scope.maxresult = 4; $scope.getBranchList = function(cpage, ppage) { $scope.branchListState = { load: true, done: false, load_more: false }; var dataSend = { 'cur_page': cpage, 'per_page': ppage }; GAEAPI.get('shop_branch/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branch = res.data; $scope.branchList = res.data.dataList; } $scope.branchListState = { load: false, done: true, load_more: false }; }); } $scope.getBranchList($scope.fetchTimes, $scope.data_per_page); $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentShopLocatorCardA', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorCardA'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { locatordata: '@locatordata', placeholderimage: '@placeholderimage', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.locatordata); console.log('locatordata : item', $scope.item); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentShopLocatorCardB', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorCardB'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { locatordata: '@locatordata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.locatordata); console.log('locatordata : item', $scope.item); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.buildIframeMapByLocline = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps?q=' + DataName; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; }; return promise; });_ui_share_app.directive('componentShopLocatorCardC', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorCardC'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { locatordata: '@locatordata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.locatordata); /*console.log('locatordata : item', $scope.item);*/ $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.branch_day = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.buildIframeMapByLocline = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps?q=' + DataName; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; }; return promise; });_ui_share_app.directive('componentShopLocatorCardD', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorCardD'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { locatordata: '@locatordata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.item = JSON.parse($scope.locatordata); /*console.log('locatordata : item', $scope.item);*/ $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.displayTelCode = function(telString) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); }; $scope.displayTelCodefax = function(telString, num) { if (telString.indexOf("+")) { var a = telString.split("+"); } return a[num]; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.branch_day = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.buildIframeMapByLocline = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps?q=' + DataName; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; }; return promise; });_ui_share_app.directive('componentShopLocatorD', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorD'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', col: '@col', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data = []; $scope.branch = []; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.branchListState = { load: true, done: false, load_more: false }; $scope.branchList = []; $scope.fetchTimes = 1; $scope.data_per_page = 12; $scope.maxresult = 4; $scope.getBranchList = function(cpage, ppage) { $scope.branchListState = { load: true, done: false, load_more: false }; var dataSend = { 'cur_page': cpage, 'per_page': ppage }; GAEAPI.get('shop_branch/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branch = res.data; $scope.branchList = res.data.dataList; } $scope.branchListState = { load: false, done: true, load_more: false }; }); } $scope.getBranchList($scope.fetchTimes, $scope.data_per_page); $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });var uiMapBrach = false; _ui_share_app.directive('componentShopLocatorDetailA', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorDetailA'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { _font: '@font', margin: '@margin', branchid: '@branchid', icon: '@icon', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.data = []; $scope.zoomBase = 16; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.$watch('branchid', function(newValue, oldValue) { if (!newValue) { return; } }); if ($scope.branchid != "" || $scope.branchid != undefined) { $scope.branchDetail = parseInt($scope.branchid); } else { $scope.branchDetail = parseInt(0); } $scope.rebuildMapByLatLng = function(latStr, lngStr) { uiMapBrach = new google.maps.Map(document.getElementById('mapComponent'), { zoom: $scope.zoomBase, center: new google.maps.LatLng(latStr, lngStr), mapTypeId: 'roadmap' }); var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; var icons = { info: { name: 'info', icon: $scope.imgPath + $scope.icon } }; var features = [{ position: new google.maps.LatLng(latStr, lngStr), type: 'info' }]; features.forEach(function(feature) { var marker = new google.maps.Marker({ position: feature.position, icon: icons[feature.type].icon, map: uiMapBrach }); }); if (uiMapBrach !== false && typeof uiMapBrach === 'object') { $("#map").hide(); } }; $scope.rebuildMapByName = function(data) { /* iframe generate */ }; $scope.branchListIdDetail = []; $scope.getBranchDetail = function() { var dataSend = { 'txt_shop_branch_id': $scope.branchDetail }; GAEAPI.get('shop_branch/id', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branchListIdDetail = res.data; console.log("shop_branch", res); /* loop */ var myLocationTimer = setInterval(function() { /* loop check if orignal init */ if (typeof map === 'object' && $("#map").html() !== "") { console.log('myLocationTimer: map', typeof map); window.clearInterval(myLocationTimer); var b = $scope.branchListIdDetail; if (b.shop_branch_map_location_array.length > 0) { /* map api */ uiMapBrach = false; $scope.rebuildMapByLatLng(parseFloat(b.shop_branch_map_location_array[0].lat), parseFloat(b.shop_branch_map_location_array[0].lng)); } else { /* ifrane */ $scope.rebuildMapByName(); } } }, 500); } else { console.log("shop_branch", res); } }); } $scope.getBranchDetail(); $scope.getOpenTableFromGoogle = function(item) { var r = []; var e = 'https://maps.google.com/maps/api/geocode/json?address='; }; $scope.makeDummy = function() { var o = function(i) { return { 'branch_id': i, 'branch_name': 'บริษัท เอ็กซ์-สปีด กรุ๊ป จำกัด', 'branch_phone': '02-979-5965-66', 'branch_mobile': '087-9999653', 'branch_description': 'สำนักงานใหญ่ detail', 'branch_short_description': 'สำนักงานใหญ่', 'branch_location_title': 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000', 'branch_location_latitude': '13.994813', 'branch_location_longtitude': '100.564529', 'branch_workingtime_array': [{ 'txt_index': 1, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, { 'txt_index': 2, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 3, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 4, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 5, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 6, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 7, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, ], 'branch_image': [{ 'image_url': 'https://image.getappeasy.com/src/images/2000/1032/0033/32033t1496650984.jpg' }] }; } var r = [o(1)]; $scope.getOpenTableFromGoogle(r[0]); return r; }; if ($scope.data.length <= 0) { $scope.getData(); } $scope.displayDayByIndex = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.displayTelCode = function(telString) { if (/\s/.test(telString)) { var newStringOld = telString.split("-"); var DataString = newStringOld.join(" "); } else { var DataString = telString; } return DataString; }; $scope.buildIframeMapByNaneLoc = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps/embed/v1/place?key=AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18&q=' + DataName; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; $scope.buildIframeMapByLoc = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps?q=' + DataName + '&output=embed&hl=th-TH'; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; $scope.buildIframeMapByLocline = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps?q=' + DataName; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; $scope.map = []; $scope.initMap = function() { $scope.map = new google.maps.Map(document.getElementById('map'), { zoom: $scope.zoomBase, center: new google.maps.LatLng(13.679963, 100.723735), mapTypeId: 'roadmap' }); }; }; return promise; });var uiMapBrach = false; _ui_share_app.directive('componentShopLocatorDetailB', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorDetailB'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { _font: '@font', margin: '@margin', branchid: '@branchid', icon: '@icon', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $http) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.data = []; $scope.zoomBase = 14; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.$watch('branchid', function(newValue, oldValue) { if (!newValue) { return; } }); if ($scope.branchid != "" || $scope.branchid != undefined) { $scope.branchDetail = parseInt($scope.branchid); } else { $scope.branchDetail = parseInt(0); } $scope.rebuildMapByLatLng = function(latStr) { uiMapBrach = new google.maps.Map(document.getElementById('mapComponent'), { zoom: $scope.zoomBase, center: new google.maps.LatLng(parseFloat(latStr[0].shop_branch_map_location_array[0].lat),parseFloat(latStr[0].shop_branch_map_location_array[0].lng)), mapTypeId: 'roadmap' }); var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/'; var icons = { info: { name: 'info', icon: 'https://openclipart.org/image/50px/svg_to_png/262009/Map-Pin.png' } }; var features = []; for (var i = 0; i < latStr.length; i++) { features.push({ position: new google.maps.LatLng(parseFloat(latStr[i].shop_branch_map_location_array[0].lat),parseFloat(latStr[i].shop_branch_map_location_array[0].lng)), type: 'info', }); } features.forEach(function(feature) { var marker = new google.maps.Marker({ position: feature.position, icon: icons[feature.type].icon, map: uiMapBrach }); }); if (uiMapBrach !== false && typeof uiMapBrach === 'object') { $("#map").hide(); } }; $scope.rebuildMapByName = function(data) { /* iframe generate */ }; $scope.branchListIdDetail = []; $scope.getBranchDetail = function() { var dataSend = { 'cur_page': 1, 'per_page':10, /*'txt_shop_branch_id': $scope.branchDetail */ }; GAEAPI.get('shop_branch/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branchListIdDetail = res.data.dataList; console.log("shop_branch", res); /* loop */ var myLocationTimer = setInterval(function() { /* loop check if orignal init */ if (typeof map === 'object' && $("#map").html() !== "") { console.log('myLocationTimer: map', typeof map); window.clearInterval(myLocationTimer); var b = $scope.branchListIdDetail; if (b[0].shop_branch_map_location_array.length > 0) { /* map api */ uiMapBrach = false; $scope.rebuildMapByLatLng(b); } else { /* ifrane */ $scope.rebuildMapByName(); } } }, 500); } else { console.log("shop_branch", res); } }); } $scope.getBranchDetail(); $scope.getOpenTableFromGoogle = function(item) { var r = []; var e = 'https://maps.google.com/maps/api/geocode/json?address='; }; $scope.makeDummy = function() { var o = function(i) { return { 'branch_id': i, 'branch_name': 'บริษัท เอ็กซ์-สปีด กรุ๊ป จำกัด', 'branch_phone': '02-979-5965-66', 'branch_mobile': '087-9999653', 'branch_description': 'สำนักงานใหญ่ detail', 'branch_short_description': 'สำนักงานใหญ่', 'branch_location_title': 'อาคาร เอ็กซ์-สปีด เลขที่ 9/69 หมู่ 1 ซอยบ้านกลาง 1/4 (เลียบคลองปะปา) ถนนปทุม-รังสิต ตำบลบ้านกลาง อำเภอเมือง จังหวัดปทุมธานี 12000', 'branch_location_latitude': '13.994813', 'branch_location_longtitude': '100.564529', 'branch_workingtime_array': [{ 'txt_index': 1, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, { 'txt_index': 2, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 3, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 4, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 5, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 6, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 1 }, { 'txt_index': 7, 'txt_open': '10:00', 'txt_close': '19:00', 'txt_is_open': 0 }, ], 'branch_image': [{ 'image_url': 'https://image.getappeasy.com/src/images/2000/1032/0033/32033t1496650984.jpg' }] }; } var r = [o(1)]; $scope.getOpenTableFromGoogle(r[0]); return r; }; if ($scope.data.length <= 0) { $scope.getData(); } $scope.displayDayByIndex = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.displayTelCode = function(telString) { if (/\s/.test(telString)) { var newStringOld = telString.split("-"); var DataString = newStringOld.join(" "); } else { var DataString = telString; } return DataString; }; $scope.buildIframeMapByNaneLoc = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps/embed/v1/place?key=AIzaSyDmUd9xXtDofVnrsSv8L7TENnBZYvW7V18&q=' + DataName; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; $scope.buildIframeMapByLoc = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps?q=' + DataName + '&output=embed&hl=th-TH'; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; $scope.buildIframeMapByLocline = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps?q=' + DataName; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; $scope.map = []; $scope.initMap = function() { $scope.map = new google.maps.Map(document.getElementById('map'), { zoom: $scope.zoomBase, center: new google.maps.LatLng(13.679963, 100.723735), mapTypeId: 'roadmap' }); }; }; return promise; });_ui_share_app.directive('componentShopLocatorDetailC', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentShopLocatorDetailC'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { branchid: '@branchid', home: '@home', branchlists: '@branchlists', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $http) { $scope._home = (typeof $scope.home == 'undefined' || $scope.home == '') ? "หน้าแรก" : $scope.home; $scope._branchlists = (typeof $scope.branchlists == 'undefined' || $scope.branchlists == '') ? "สาขาทั้งหมด" : $scope.branchlists; $scope.displayTelCode = function(telString) { if (telString != undefined) { if (telString.indexOf("-")) { var a = telString.split("-"); var b = a.join("").trim(); } else { var b = telString.trim(); } return b.substr(1, b.length); } }; $scope._getPostIdFromURL = function() { var test = $scope.branchid; var a = $scope.branchid; if (typeof $routeParams.branch_id !== 'undefined') { test = parseInt($routeParams.branch_id); a = $routeParams.branch_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; // $scope.$watch('branchid', function(newValue, oldValue) { // if (!newValue) { // return; // }else{ // $scope.getBranchDetail($scope._getPostIdFromURL()); // } // }); $scope.branchListIdDetail = []; $scope.getBranchDetail = function() { var dataSend = { 'txt_shop_branch_id': $scope._getPostIdFromURL(), }; GAEAPI.get('shop_branch/id', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branchListIdDetail = res.data; console.log("shop_branch", res); } else { console.log("shop_branch", res); } }); }; $scope.getBranchDetail(); $scope.displayDayByIndex = function(i) { switch (parseInt(i)) { case 1: return 'อาทิตย์'; break; case 2: return 'จันทร์'; break; case 3: return 'อังคาร'; break; case 4: return 'พุธ'; break; case 5: return 'พฤหัสบดี'; break; case 6: return 'ศุกร์'; break; case 7: return 'เสาร์'; break; default: return '-'; break; } }; $scope.buildIframeMapByLocline = function(name, lat, lng) { var newName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); var DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps?q=' + DataName; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName + '&output=embed&hl=th-TH'; }; $rootScope.$on('repeatend', function() { /* Slider Send */ var optionsParmas = { autoplay: true, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, infinite: true }; var extraOptions = { animate: false }; $timeout(function() { sliderProvider("#gallery_slider", optionsParmas, "", "", extraOptions); }, 500); }); $scope._slickGoLeft = function() { $timeout(function() { $('#gallery_slider').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('#gallery_slider').slick('slickNext'); }, 100); }; /* Click SLick Item */ $scope.slickGoto = function(idx) { $timeout(function() { $('#gallery_slider').slick('slickGoTo', idx); }, 100); }; }; return promise; });_ui_share_app.directive('componentShopLocatorE', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorE'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', col: '@col', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data = []; $scope.branch = []; $scope.getData = function() { var d = {}; $scope.data = $scope.makeDummy(); }; $scope.branchListState = { load: true, done: false, load_more: false }; $scope.branchList = []; $scope.fetchTimes = 1; $scope.data_per_page = 60; $scope.maxresult = 4; $scope.getBranchList = function(cpage, ppage) { $scope.branchListState = { load: true, done: false, load_more: false }; var dataSend = { 'cur_page': cpage, 'per_page': ppage }; GAEAPI.get('shop_branch/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.branch = res.data; $scope.branchList = res.data.dataList; } $scope.branchListState = { load: false, done: true, load_more: false }; }); } $scope.getBranchList($scope.fetchTimes, $scope.data_per_page); $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentShopLocatorMenuDropdownA', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorMenuDropdownA'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { _font: '@font', imgpath: '@imgpath', _menustart: '@menustart', _color: '@color', _backgroundcolor: '@backgroundcolor', _backgroundcolordropdown: '@backgroundcolordropdown', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.activeMenu = function() { if (!angular.element('._heading').hasClass('active')) { angular.element('._heading').addClass('active') } else { angular.element('._heading').removeClass('active') } }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._heading = ''; $scope.getHeading = function() { if (typeof $scope._viewRouteParams().branchname !== 'undefined' && typeof $scope._viewRouteParams().branchname != '') { $scope._heading = $scope._viewRouteParams().branchname; } else { $scope._heading = $scope._menustart; } } $scope.getHeading(); $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.myFunctionDropdown = function() { $scope.activeMenu(); document.getElementById("myDropdown").classList.toggle("show"); } $scope.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } } $scope._page_branch = false; $scope._get_page_branch = function() { var dataSend = { 'cur_page': 1, 'per_page': 50, }; GAEAPI.get('shop_branch/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._page_branch = res.data.dataList; } }); }; $scope._get_page_branch(); $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentShopLocatorTypeMaeju', function($rootScope, $routeParams) { var templateName = 'componentShopLocatorTypeMaeju'; var componentMain = 'componentShopLocator'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('componentShopLocatorTypeMaeju : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(load, done) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : load : ", load); _self.consoleLog("getData : done : ", done); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: load, done: done }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(res) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : res : ", res); _self.consoleLog("getData : ", "------- getApi -------"); callback(res); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.setData = { cur_page: 1, per_page: 8, total_rows: 0, total_rows_state: { load: false, done: false }, api: 'shop_branch/lists', dataSend: {}, state: { load: false, done: false }, dataArray: [] }; $scope.getData().getRouteParams(function(params) { $scope.setData.state = $scope.getData().stateData(true, false); $scope.setData.dataSend = { 'cur_page': $scope.setData.cur_page, 'per_page': $scope.setData.per_page }; $scope.getData().dataSend($scope.setData.api, $scope.setData.dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(res) { $scope.setData.total_rows = res.data.total_rows; $scope.setData.dataArray = res.data.dataList; $scope.setData.state = $scope.getData().stateData(false, true); }); }); }); $scope.loadMore = function() { if (!$scope.setData.total_rows_state.load) { $scope.setData.cur_page++; $scope.setData.total_rows_state = $scope.getData().stateData(true, false); $scope.getData().getRouteParams(function(params) { $scope.setData.dataSend = { 'cur_page': $scope.setData.cur_page, 'per_page': $scope.setData.per_page }; $scope.getData().dataSend($scope.setData.api, $scope.setData.dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(res) { if ($scope.setData.dataArray.length < res.data.total_rows) { $scope.setData.total_rows = res.data.total_rows; var oldData = $scope.setData.dataArray; $scope.setData.dataArray = oldData.concat(res.data.dataList); } else { $scope.setData.cur_page--; } $scope.setData.total_rows_state = $scope.getData().stateData(false, false); }); }); }); } }; }; return promise; });_ui_share_app.directive('componentShopLogo', function() { var templateName = 'componentShopLogo'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.link = function(scope, element, attr) { var parentElement = element.parent(); /*element.parent().find('img').hide();*/ var imageVirtual_Attr = ""; /* height */ if (element.attr('height')) { imageVirtual_Attr += ' height="' + element.attr('height') + '" '; } /* width */ if (element.attr('width')) { imageVirtual_Attr += ' width="' + element.attr('width') + '" '; } /* class */ if (element[0].classList !== '') { imageVirtual_Attr += ' class="' + element[0].classList + '" '; } /* style */ imageVirtual_Attr += ' style="'; if (element[0].style.width !== '') { imageVirtual_Attr += 'width:' + element[0].style.width + '; '; } if (element[0].style.height !== '') { imageVirtual_Attr += 'height:' + element[0].style.height + '; '; } if (element[0].style.maxWidth !== '') { imageVirtual_Attr += 'max-width:' + element[0].style.maxWidth + '; '; } if (element[0].style.maxHeight !== '') { imageVirtual_Attr += 'max-height:' + element[0].style.maxHeight + '; '; } /*if(element[0].style.opacity!==''){ imageVirtual_Attr += 'max-height:'+element[0].style.opacity+'; '; } if(element[0].style.transform!==''){ imageVirtual_Attr += 'max-height:'+element[0].style.transform+'; '; }*/ imageVirtual_Attr += '"'; function buildLogo(type, logoLight, logoDark, logoGlyph) { switch (type) { case 'light': if (logoLight != '') { element.addClass('force-dispaly-none'); parentElement.append(''); return; } break; case 'dark': if (logoDark != '') { element.addClass('force-dispaly-none'); parentElement.append(''); } break; case 'glyph': if (logoGlyph != '') { element.addClass('force-dispaly-none'); parentElement.append(''); } break; case 'background_image_light': if (logoLight != '') { element.addClass('force-dispaly-none'); parentElement.append('
'); return; } break; case 'background_image_dark': if (logoDark != '') { element.addClass('force-dispaly-none'); parentElement.append('
'); } break; case 'background_image_glyph': if (logoGlyph != '') { element.addClass('force-dispaly-none'); parentElement.append('
'); } break; } } var shopData = UiShop.get.shopData() || undefined; if (shopData != undefined || typeof shopData !== 'undefined') { var logoLight = (shopData.shop_logo.logo_light.length) ? shopData.shop_logo.logo_light[0].image_url : ''; var logoDark = (shopData.shop_logo.logo_dark.length) ? shopData.shop_logo.logo_dark[0].image_url : ''; var logoGlyph = (shopData.shop_logo.logo_glyph.length) ? shopData.shop_logo.logo_glyph[0].image_url : ''; return buildLogo(attr.logo, logoLight, logoDark, logoGlyph); } else { GAEAPI.get('shop/current', {}, scope).then(function(e) { if (e.ok == 1) { var logoLight = (e.data.shop_logo.logo_light.length) ? e.data.shop_logo.logo_light[0].image_url : ''; var logoDark = (e.data.shop_logo.logo_dark.length) ? e.data.shop_logo.logo_dark[0].image_url : ''; var logoGlyph = (e.data.shop_logo.logo_glyph.length) ? e.data.shop_logo.logo_glyph[0].image_url : ''; return buildLogo(attr.logo, logoLight, logoDark, logoGlyph); } }); } } return promise; });_ui_share_app.directive('componentSlideImage', function($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentSlideImage'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size: '@size', margin: '@margin', callback: '@callback', imgpath: '@imgpath', dataimg: '@dataimg', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.indeta = []; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 6; i++){ r.push({ banner_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/180x150.jpg'}], callback_array:true }); } return r; }; $scope.data = []; $scope.data_desktop = []; $scope.data_mobile = []; $scope.type = 'carouselMini'; $scope.done = false; $scope.prev_win_size = $(window).width(); GAEAPI.get('web/home', {}, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.mini_banner.banner_array; if(resultArray.length <= 0){ if(typeof $scope.callback !== 'undefined' && $scope.callback !== ''){ $scope.data_desktop = $scope.watchCallbackArray(); $scope.data_mobile = $scope.watchCallbackArray(); $scope.done = true; return; } } else { var dummyArray = []; var dummyArray_mobile = []; for(var i = 0; i < resultArray.length; i++){ if($scope._showWeb(resultArray[i].banner_badge)){ dummyArray.push(resultArray[i]); } if($scope._showApp(resultArray[i].banner_badge)){ dummyArray_mobile.push(resultArray[i]); } } $scope.data_desktop = dummyArray; $scope.data_mobile = dummyArray_mobile; $scope.done = true; /*var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); */ } }); $scope.viewData = function(){ return ($(window).width() > 991) ? $scope.data_desktop : $scope.data_mobile; }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function() { return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function() { var elementName = '.component_carousel_map[data-id="' + $scope._key() + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); angular.element($window).bind('resize', function() { if ($scope.prev_win_size != $(window).width()) { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } setTimeout(function() { if ($(elementName).hasClass('slick-initialized') || $(elementName).hasClass('slick-slider')) { $(elementName).slick('unslick'); } sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }, 3000); } }); }; $scope.checkHide = function() { var r = false; if (angular.element('.component_carousel_map.slick-initialized[data-id="' + $scope._key() + '"]').length) { r = true; } return r; }; $scope.viewLink = function(i) { $window.location.href = i; }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; /* Watch when finish repeat */ $rootScope.$on('repeatend', function() { if ($('.component_carousel_map[data-id="' + $scope._key() + '"]').not('.slick-initialized')) { $timeout(function() { $scope.initSlider(); }, 500); } }); }; return promise; });_ui_share_app.directive('componentSocialShare', function($rootScope, $routeParams, metaRender) { var templateName = 'componentSocialShare'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id: '@id', title: '@title', type: '@type', name: '@name', icon: '@icon', iconcolor: '@iconcolor', iconcolorhover: '@iconcolorhover', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope._iconcolor = ($scope.iconcolor != undefined && $scope.iconcolor != "") ? $scope.iconcolor : "grey2@2x"; $scope._iconcolorhover = ($scope.iconcolorhover != undefined && $scope.iconcolorhover != "") ? $scope.iconcolorhover : "color@2x"; $scope.iconType = (typeof $scope.icon !== 'undefined' && $scope.icon == 'fill') ? 'fill' : 'outline'; $scope.getCurrentUrl = function(uniqueId) { if ($scope.type == 'product-detail' && window.location.href.indexOf('product-detail') == -1) { if (GURL.isHtml5Mode()) { return CUR_THEME.data.app_url + 'product-detail/' + uniqueId + '?p=' + uniqueId; } else { return CUR_THEME.data.app_url + '?p=' + uniqueId + '#/product-detail/' + uniqueId; } } return window.location.href; }; $scope._viewMeta = function(name, pageType, uniqueId) { if (!GURL.isHtml5Mode()) { if (pageType === 'blogDetail') { return CUR_THEME.data.app_url + '?bd=' + uniqueId + '#/blog-detail/' + uniqueId; } else if (pageType === 'productDetail') { return CUR_THEME.data.app_url + '?p=' + uniqueId + '#/product-detail/' + uniqueId; } else if (pageType === 'pageDetail') { return CUR_THEME.data.app_url + '?pd=' + uniqueId + '#/pages/' + uniqueId; } else if (pageType === 'promotionDetail') { return CUR_THEME.data.app_url + '?pd=' + uniqueId + '#/promotion-detail/' + uniqueId; } } else { return $scope.getCurrentUrl(uniqueId); } }; }; return promise; });_ui_share_app.directive('componentSocialShareB', function($rootScope, $routeParams, metaRender) { var templateName = 'componentSocialShareB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id: '@id', title: '@title', type: '@type', name: '@name', version: '@version', icon: '@icon', iconhover: '@iconhover', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.getCurrentUrl = function() { return (window.location.href); /*encodeURIComponent*/ }; $scope._viewMeta = function(name, pageType, uniqueId) { return $scope.getCurrentUrl(); /*return metaRender.get(name, pageType, uniqueId);*/ }; }; return promise; });_ui_share_app.directive('componentSocialnetworkA', function ($rootScope, $routeParams) { var templateName = 'componentSocialnetworkA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; /* * check if fail data then return callback dummy * @params {currentShop} * @return true | false */ $scope.callback = false; $scope.checkFail = function(currentShop){ if(typeof currentShop.shop_extend_data.facebook_url == 'undefined' && typeof currentShop.shop_extend_data.google_url == 'undefined' && typeof currentShop.shop_extend_data.instragram_url == 'undefined' && typeof currentShop.shop_extend_data.line_url == 'undefined'){ $scope.callback = true; } }; /* * Get shop data * @params none * @return array */ $scope.dataArray = []; $scope.line_friends = []; $scope.shopCurrentData = false; $scope.getData = function(){ $scope.dataArray = []; GAEAPI.get('shop/current',{},$scope).then(function(e){ console.log("shopCurrent",e); if(e.ok == 1){ $scope.shopCurrentData = e.data; angular.forEach(e.data.shop_extend_data, function(i,key){ if(key !== 'line_id'){ var obJect = $scope.buildSocialItemObject(key,i); $scope.dataArray.push(obJect); } }); } $scope.checkFail(e.data); }); }; $scope.getData(); /* * build object for social array * @params socialName (string) * @params socialValue (string) * @return object */ $scope.buildSocialItemObject = function(socialName,socialValue){ var nameSplit = socialName.split("_"); if(nameSplit[0] == 'instragram'){ nameSplit[0] = 'ig'; } // var promiseObject = { // 'txt_social_name': nameSplit[0], // 'txt_social_full_name': socialName, // 'txt_social_value': socialValue||'' // }; var promiseObject = { 'txt_social_name': nameSplit[0], 'txt_social_full_name': socialName, 'txt_social_value': socialValue||'', 'txt_icon' : nameSplit[0], 'txt_icnt_icon' : ($scope.icnticon !== "" && $scope.icnticon !== undefined)? $scope.icnticon :"icnt_fill_", 'txt_icnt_icon_hover' : ($scope.icnticonhover !== "" && $scope.icnticonhover !== undefined)? $scope.icnticonhover :"icnt_fill_", }; if(socialName.indexOf('line_url')!=-1){ if(promiseObject.txt_social_value!=""){ if(promiseObject.txt_social_value.indexOf('@') !== -1 || promiseObject.txt_social_value.indexOf('%40')){ var n = promiseObject.txt_social_value.replace('@','%40'); promiseObject.txt_social_value = 'http://line.me/ti/p/' + n; } else { promiseObject.txt_social_value = 'http://line.me/ti/p/~' + promiseObject.txt_social_value; } $scope.line_friends[0] = promiseObject; } else { promiseObject.txt_social_value = ''; } } /*console.log("shopCurrent: obj: ",promiseObject);*/ return promiseObject; }; /* Get Shop Link */ $scope.app_url = function(){ return CUR_THEME.app_url(); }; }; return promise; }); _ui_share_app.directive('componentSocialnetworkB', function($rootScope, $routeParams) { var templateName = 'componentSocialnetworkB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', size: '@size', type: '@type', icnticon: '@icnticon', icon: '@icon', icnticonhover: '@icnticonhover', iconhover: '@iconhover', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * Get shop data * @params none * @return array */ $scope.dataArray = []; $scope.line_friends = []; $scope.getData = function() { $scope.dataArray = []; GAEAPI.get('shop/current', {}, $scope).then(function(e) { if(e.ok == 1){ $scope.shopCurrentData = e.data; /* console.log("getData : e.data.shop_extend_data : ",e.data.shop_extend_data); */ angular.forEach(e.data.shop_extend_data, function(i,key){ /* console.log("getData : key : ",key); */ if(key != 'line_id' && key != 'instagram_url'){ /* console.log("getData : key : ok : ",key); */ var obJect = $scope.buildSocialItemObject(key,i); $scope.dataArray.push(obJect); } }); } }); }; $scope.getData(); /* * build object for social array * @params socialName (string) * @params socialValue (string) * @return object */ $scope.getTel = function(number, callback) { var res_number = ""; if (number != '' && number != undefined) { if (number.indexOf("-") != -1) { var number_array = number.split("-"); var number_array_sum = number_array.join("").trim(); res_number = number_array_sum.substr(1, number_array_sum.length); } else { res_number = number.substr(1, number.length); } } res_number = "tel:+66" + res_number; callback(res_number); }; $scope.getMailto = function(email, callback) { var res_email = ""; res_email = (email != '') ? "mailto:" + email : ''; callback(res_email); }; $scope.buildSocialItemObject = function(socialName, socialValue) { var nameSplit = socialName.split("_"); if(nameSplit[0] == 'instagram' || nameSplit[0] == 'instragram'){ nameSplit[0] = 'ig'; } var promiseObject = { 'txt_social_name': nameSplit[0], 'txt_social_full_name': socialName, 'txt_social_value': socialValue||'', 'txt_icon' : nameSplit[0], 'txt_icnt_icon' : ($scope.icnticon !== "" && $scope.icnticon !== undefined)? $scope.icnticon :"icnt_fill_", 'txt_icnt_icon_' : ($scope.icon !== "" && $scope.icon !== undefined)? $scope.icon : "01_grey1@2x", 'txt_icnt_icon_hover' : ($scope.icnticonhover !== "" && $scope.icnticonhover !== undefined)? $scope.icnticonhover :"icnt_fill_", 'txt_icnt_icon_hover_' : ($scope.iconhover !== "" && $scope.iconhover !== undefined)? $scope.iconhover : "01_color@2x", }; if(socialName.indexOf('line_url')!=-1){ if(promiseObject.txt_social_value!=""){ if(promiseObject.txt_social_value.indexOf('@') !== -1 || promiseObject.txt_social_value.indexOf('%40')){ var n = promiseObject.txt_social_value.replace('@','%40'); promiseObject.txt_social_value = 'http://line.me/ti/p/' + n; } else { promiseObject.txt_social_value = 'http://line.me/ti/p/~' + promiseObject.txt_social_value; } $scope.line_friends[0] = promiseObject; } else { promiseObject.txt_social_value = ''; } } else if (socialName.indexOf('social_email') != -1) { promiseObject.txt_icon = "mail"; promiseObject.txt_icnt_icon = "icnt_fill_"; promiseObject.txt_icnt_icon_hover = "icnt_fill_"; if(promiseObject.txt_social_value !== "") $scope.getMailto(promiseObject.txt_social_value,function(res) { promiseObject.txt_social_value = res; }); } else if (socialName.indexOf('social_mobile') != -1) { promiseObject.txt_icon = "phone"; promiseObject.txt_icnt_icon = "icnt_fill_"; promiseObject.txt_icnt_icon_ = "01_grey1@2x"; promiseObject.txt_icnt_icon_hover = "icnt_fill_"; if(promiseObject.txt_social_value !== "") $scope.getTel(promiseObject.txt_social_value,function(res) { promiseObject.txt_social_value = res; }); } /* console.log("getData : promiseObject : ",promiseObject); */ return promiseObject; }; /* Get Shop Link */ $scope.app_url = function() { return CUR_THEME.app_url(); }; $scope.shopFollowUs = function() { var shop_id = CUR_THEME.shop_id(); if (shop_id == 762) { return true; } else { return false; } }; }; return promise; });_ui_share_app.directive('componentSocialnetworkC', function($rootScope, $routeParams) { var templateName = 'componentSocialnetworkC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', size: '@size', type: '@type', icnticon: '@icnticon', icon: '@icon', icnticonhover: '@icnticonhover', iconhover: '@iconhover', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * Get shop data * @params none * @return array */ $scope.dataArray = []; $scope.line_friends = []; $scope.consoleLog = function(text, data) { var show = true; if (show) { console.log(text, data); } }; $scope.getData = function() { $scope.dataArray = []; GAEAPI.get('shop/current', {}, $scope).then(function(output) { $scope.consoleLog("getData : shop/current : output : ", output); if (output.ok == 1) { $scope.shopCurrentData = output.data; $scope.consoleLog("getData : shop/current : output.data.shop_extend_data : ", output.data.shop_extend_data); angular.forEach(output.data.shop_extend_data, function(i, key) { $scope.consoleLog("getData : angular : i : ", i); $scope.consoleLog("getData : angular : key : ", key); if (key != 'line_id' && key != 'instagram_url') { $scope.consoleLog("getData : angular : if : i : ", i); $scope.consoleLog("getData : angular : if : key : ", key); var obJect = $scope.buildSocialItemObject(key, i); $scope.consoleLog("getData : obJect : ", obJect); $scope.dataArray.push(obJect); } }); } }); }; $scope.getData(); /* * build object for social array * @params socialName (string) * @params socialValue (string) * @return object */ $scope.buildSocialItemObject = function(socialName, socialValue) { $scope.consoleLog("buildSocialItemObject : socialName : ", socialName); $scope.consoleLog("buildSocialItemObject : socialValue : ", socialValue); var nameSplit = socialName.split("_"); if (nameSplit[0] == 'instagram' || nameSplit[0] == 'instragram') { nameSplit[0] = 'ig'; } if (nameSplit[1] == 'email') { nameSplit[0] = 'mail'; } var promiseObject = { 'txt_social_name': nameSplit[0], 'txt_social_full_name': socialName, 'txt_social_value': socialValue || '' }; if (socialName.indexOf('line_url') != -1) { if (promiseObject.txt_social_value != "") { if (promiseObject.txt_social_value.indexOf('@') !== -1 || promiseObject.txt_social_value.indexOf('%40')) { var n = promiseObject.txt_social_value.replace('@', '%40'); promiseObject.txt_social_value = 'http://line.me/ti/p/' + n; } else { promiseObject.txt_social_value = 'http://line.me/ti/p/~' + promiseObject.txt_social_value; } $scope.line_friends[0] = promiseObject; } else { promiseObject.txt_social_value = ''; } } /*console.log("shopCurrent: obj: ",promiseObject);*/ return promiseObject; }; /* Get Shop Link */ $scope.app_url = function() { return CUR_THEME.app_url(); }; }; return promise; });_ui_share_app.directive('componentSpecification', function ($rootScope, $routeParams) { var templateName = 'componentSpecification'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { id:'@id', type:'@type', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * Get product id * @params {id} product id * @return objectData */ $scope.data = false; $scope.getData = function(id){ $scope.data = false; GAEAPI.get('product/id',{'txt_product_id':id},$scope).then(function(e){ if(e.ok == 1){ $scope.data = e.data; console.log("spec",e); } }); }; $scope.$watch('id', function(newValue, oldValue){ if(!newValue||newValue==0) return; $scope.getData(newValue); }); $scope.checkType = function(){ if(typeof $scope.type == 'undefined' || $scope.type == '' || !angular.isDefined($scope.type)){ return 1; } return $scope.type; }; }; return promise; }); _ui_share_app.factory('$componentTag', function componentTag($routeParams, $timeout) { return });_ui_share_app.directive('componentTagA', function($rootScope, $routeParams) { var templateName = 'componentTagA'; var componentMain = 'componentTag'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', stylebutton : '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data_per_page = 8; $scope.JsonDATA = []; $scope.JsonProductArray = []; $scope.JsonProductArrayState = { load: false, done: false }; $scope.getJsonProductArray = function(page, sen) { $scope.JsonProductArrayState = $scope.StateData(true, false); var dataSend = { 'cur_page': 1, 'per_page': page, 'txt_filter_json': JSON.stringify({ 'tags': sen }) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope.JsonDATA = output.data; $scope.JsonProductArray = output.data.dataList; } $scope.JsonProductArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.getJsonProductArray($scope.data_per_page, $scope._viewRouteParams().send); $scope.loadMore = function() { $scope.data_per_page = parseInt($scope.data_per_page) + 8; $scope.getJsonProductArray($scope.data_per_page, $scope._viewRouteParams().send); }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentTagListsA', function($rootScope, $routeParams) { var templateName = 'componentTagListsA'; var componentMain = 'componentTag'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.JsonTagsDATA = []; $scope.JsonTagsArrayState = { load: false, done: false }; $scope.getJsonProductArray = function(page, sen) { $scope.JsonTagsArrayState = $scope.StateData(true, false); var dataSend = { 'cur_page': 1, 'per_page': 50 }; GAEAPI.get('tag/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope.JsonTagsDATA = output.data.dataList; } $scope.JsonTagsArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getJsonProductArray(); $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentTagListsProductA', function($rootScope, $routeParams) { var templateName = 'componentTagListsProductA'; var componentMain = 'componentTag'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.JsonTagsDATA = []; $scope.tagsProductDATA = []; $scope.data_Tags_done = false; $scope.getJsonTagsArray = function() { var dataSend = { 'cur_page': 1, 'per_page': 20 }; GAEAPI.get('tag/lists', dataSend, $scope).then(function(output) { console.log("output :", output); if (output.ok == 1) { $scope.JsonTagsDATA = output.data.dataList; /*console.log("output : 0", $scope.JsonTagsDATA);*/ $scope.jsonProductArray(0, $scope.JsonTagsDATA, function(resultFromArray) { if (!resultFromArray) { /* No data */ } else {} /*console.log("output : 1", resultFromArray);*/ $scope.data_Tags_done = true; if (resultFromArray.length) { var productPrintArray = []; for (var i = 0; i < resultFromArray.length; i++) { $scope.getProductByTag(resultFromArray[i], function(tagRequest, resultProduct) { /*console.log('output : 2', tagRequest, ':', resultProduct);*/ var dataObject = { 'tag_name': tagRequest, 'tag_product_array': resultProduct }; $scope.tagsProductDATA.push(dataObject); console.log('output : 3', dataObject); console.log('output : 4', $scope.tagsProductDATA); }); } } }); } }); }; $scope.getJsonTagsArray(); $scope.getProductByTag = function(tagString, callback) { var dataSend = { cur_page: 1, per_page: 10, txt_filter_json: JSON.stringify({ "tags": tagString, "badge_id_array": [16] }) }; GAEAPI.get('product/lists', dataSend).then(function(result) { if (result.ok == 1) { if (callback != undefined) { callback(tagString, result.data.dataList); } } }); }; $scope.jsonProductArray = function(index, tagDataArray, callback) { if (tagDataArray.length <= index) { if (callback) { callback(false); } return false; } var result = []; for (var index in tagDataArray) { var pushData = tagDataArray[index]; var tag_id = GAEAPI.getValue(pushData["tag_id"], ""); var tag_name = GAEAPI.getValue(pushData["tag_name"], ""); if (tag_id != "" && tag_name != "") { result.push(pushData); } } var tagStringArray = []; for (var idx in tagDataArray) { if (tagDataArray[idx].tag_name != "") { tagStringArray.push(tagDataArray[idx].tag_name); } } if (callback != undefined) { callback(tagStringArray); } } $scope.GETDataArrayLength = function(input) { return input.length; } $scope.DataArrayOne = function(input) { var data = input.length; var output = {}; var data = data / 2; for (var i = 0; i < data; i++) { output[i] = input[i]; } return output; }; $scope.DataArrayTwo = function(input) { var data = input.length; var output = {}; data = Math.ceil(data / 2); for (var i = data; i < input.length; i++) { output[i] = input[i]; } return output; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.mkCarouselProduct = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 2, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 2, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.setdispay = function(imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow', 'hidden'); } $scope.setdispayclose = function(imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow', 'visible'); } $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; }; return promise; });_ui_share_app.directive('componentTagSendProductA', function($rootScope, $routeParams) { var templateName = 'componentTagSendProductA'; var componentMain = 'componentTag'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { margin: '@margin', send: '@send', referral: '@referral', dataimage: '@dataimage', dataicon: '@dataicon', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.tagsProductDATA = []; $scope.tagsProductDATAState = { load: false, done: false }; $scope.getProductByTag = function(tagString) { $scope.tagsProductDATAState = $scope.StateData(true, false); var dataSend = { cur_page: 1, per_page: 10, txt_filter_json: JSON.stringify({ "tags": tagString, "badge_id_array": [16] }) }; console.log("dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { if (output.ok == 1) { $scope.tagsProductDATA = output.data.dataList; } $scope.tagsProductDATAState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getProductByTag($scope.send); $scope.categoryByIdData = []; $scope.getCategoryById = function(id) { var dataSend = { txt_referral_id: id }; console.log("categoryByIdData : ", dataSend); GAEAPI.get('referral/id_map', dataSend).then(function(output) { if (output.ok == 1) { $scope.categoryByIdData = output.data; } }); }; $scope.getCategoryById($scope.referral); $scope.GETDataArrayLength = function(input) { return input.length; } $scope.DataArrayOne = function(input) { var data = input.length; var output = {}; var data = data / 2; for (var i = 0; i < data; i++) { output[i] = input[i]; } return output; }; $scope.DataArrayTwo = function(input) { var data = input.length; var output = {}; data = Math.ceil(data / 2); for (var i = data; i < input.length; i++) { output[i] = input[i]; } return output; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.mkCarouselProduct = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 2, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 2, } }, { breakpoint: 991, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 768, settings: { arrows: false, slidesToShow: 2 } }, { breakpoint: 480, settings: { arrows: false, slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.setdispay = function(imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow', 'hidden'); } $scope.setdispayclose = function(imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow', 'visible'); } $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } $scope.calculateDiscount = function(expensivePrice, salePrice) { var dif = expensivePrice - salePrice; return parseInt(dif * 100 / expensivePrice); }; }; return promise; });_ui_share_app.directive('componentTestCart', function($rootScope, $routeParams, $location) { var templateName = 'componentTestCart'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'one': '?one', 'two': '?two', 'three': '?three', }; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope._component = "componentTesterCart"; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope.getData = function() { var getFunction = { consoleLog: function(functionName, data) { console.log($scope._component, ' : ', functionName, ' : ', data); }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams params", params); callback(params, state); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend api", api); _self.consoleLog("dataSend dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi api", api); _self.consoleLog("getApi dataSend", dataSend); _self.consoleLog("getApi res_api", res_api); state = _self.stateData(false, true); callback(res_ok, res_api, state); }) }); }, storeGet: function(callback) { var _self = this; var store_gae_cart_id = store.get('gae_cart_id'); var store_state = (typeof store != 'undefined') ? true : false; var store_get_state = (typeof store.get('gae_cart_id') != 'undefined') ? true : false; _self.consoleLog("storeGet store", store); _self.consoleLog("storeGet store_state", store_state); _self.consoleLog("storeGet store_state", store_state); _self.consoleLog("storeGet store_get_state", store_get_state); callback(store, store_gae_cart_id, store_state, store_get_state); }, gaeCartId: function(callback) { var _self = this; _self.storeGet(function(res_store, res_store_gae_cart_id, res_store_state, res_store_get_state) { var dataSend = {}; if (res_store_state && res_store_get_state) { dataSend.txt_cart_id = res_store_gae_cart_id; } _self.consoleLog("gaeCartId dataSend", dataSend); callback(dataSend); }); }, buildTitleUrl: function(title) { var build_title = title.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return build_title; }, main: function() { var _self = this; } } return getFunction; }; $scope.dataApi = { cart: { dataSend: {}, api: "cart/current", ok: false, dataArray: [], dataArrayState: { load: false, done: false } } }; $scope.getData().getRouteParams(function(res_params, res_state) { $scope.dataApi.cart.dataArrayState = res_state; $scope.getData().gaeCartId(function(res_dataSend) { $scope.dataApi.cart.dataSend = res_dataSend; $scope.getData().dataSend($scope.dataApi.cart.api, $scope.dataApi.cart.dataSend, function(res_api, res_dataSend) { $scope.getData().getApi(res_api, res_dataSend, function(res_ok, get_res_api, res_state) { $scope.dataApi.cart.ok = res_ok; $scope.dataApi.cart.dataArray = get_res_api.data; $scope.dataApi.cart.dataArrayState = res_state; }); }); }); }); }; return promise; });_ui_share_app.directive('componentTextSlide', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentTextSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', margin: '@margin', datafontcolor: '@datafontcolor', dataratio: '@dataratio', dataweight: '@dataweight', callback: '@callback', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $http) { console.log("datafontcolor :", $scope.datafontcolor); $scope.currentShopId = parseInt(CUR_THEME.shop_id()); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.isData = false; $scope._textSlide = []; $scope._gettextslide = function() { $scope._textslide_data = []; var shopInt = parseInt(CUR_THEME.shop_id()); GAEAPI.get('web/home', {}).then(function(res) { if (res.ok == 1) { $scope._textSlide = res.data.textslide_banner; $scope.isData = true; if (!$scope._textSlide.banner_array.length && typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope._textSlide.banner_array = [{ 'banner_header': 'An intro text in text slide 1', 'banner_sub_header': 'Text in the middle of slide 1', 'banner_footer': 'Bottom text slide 1' }, { 'banner_header': 'An intro text in text slide 2', 'banner_sub_header': 'Text in the middle of slide 2', 'banner_footer': 'Bottom text slide 2' }, ]; } /*var a = $interval(function(){ if($scope._uniqueKey != ''){ $interval.cancel(a); $scope.mkCarouselTwo(); } },1000);*/ } }); }; $scope._gettextslide(); $scope.mkCarousel1 = function(elem) { setTimeout(function() { var carousel = $('.' + elem); var is_dark; carousel.not('.slick-initialized').slick({ autoplay: false, slidesToShow: 1, dots: true }).addClass('active'); }, 1000); }; $scope.mkCarouselTwo = function() { $('.text_slider_container[data-id=' + $scope._key() + ']').slick({ dots: true, autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }); }; $scope._ratio = []; $scope._weight = []; $scope.$watch('dataratio', function(newValue, oldValue) { if (!newValue) { return; } $scope._ratio = newValue.toString().split(","); }); $scope.$watch('datafontcolor', function(newValue, oldValue) { if (!newValue) { return; } $scope._fontcolor = newValue.toString().split(","); }); $scope.$watch('dataweight', function(newValue, oldValue) { if (!newValue) { return; } $scope._weight = newValue.toString().split(","); }); $scope.getRatio = function(n) { if (typeof $scope._ratio == 'undefined') { return } if (typeof $scope._ratio[n] !== 'undefined' && $scope._ratio[n] != '') { return $scope._ratio[n]; } return '0.7'; }; $scope.getFontcolor = function(n) { if (typeof $scope._fontcolor == 'undefined') { return } if (typeof $scope._fontcolor[n] !== 'undefined' && $scope._fontcolor[n] != '') { return $scope._fontcolor[n]; } return '#000'; }; $scope.getWeight = function(n) { if (typeof $scope._weight == 'undefined') { return } if (typeof $scope._weight[n] !== 'undefined' && $scope._weight[n] != '') { return $scope._weight[n]; } return 'normal'; }; $scope.style_name = ''; $scope.style = function(shop_name) { var name = shop_name; if (name == 'thaitens') { $scope.style_name = name; } else { $scope.style_name = 'undefined'; } }; $scope.style($scope.name); /* Watch when finish repeat */ $scope.slideReady = false; $rootScope.$on('repeatend', function() { $scope.slideReady = true; }); $scope.sliderTimer = null; $scope.intervalTextSliderCheck = 0; /*if(parseInt(CUR_THEME.shop_id()) == 507){*/ var timeoutTextSliderCheck = 0; var elementName = '.tttttttttttttt'; var configSliderTxt = { dots: true, autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600 }; $scope.intervalTextSliderCheck = $interval(function() { if ($scope.isData) { if ($scope._textSlide.banner_array.length && $(elementName).length) { $interval.cancel($scope.intervalTextSliderCheck); timeoutTextSliderCheck = $timeout(function() { $timeout.cancel(timeoutTextSliderCheck); $(elementName).slick(configSliderTxt); }, 1000); } } }, 500); /*} else { angular.element(window).bind('load', function(){ var timeoutTextSliderCheck = 0; var elementName = '.tttttttttttttt'; var configSliderTxt = { dots: true, autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600 }; $scope.intervalTextSliderCheck = $interval(function(){ if($scope._textSlide.banner_array.length && $(elementName).length){ $interval.cancel($scope.intervalTextSliderCheck); timeoutTextSliderCheck = $timeout(function(){ $timeout.cancel(timeoutTextSliderCheck); $(elementName).slick(configSliderTxt); }, 1000); } },500); }); }*/ }; return promise; }); if (CUR_THEME.shop_id() == 507) {}_ui_share_app.directive('componentTextSlideA', function($rootScope, $routeParams) { var templateName = 'componentTextSlideA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', datafontcolor: '@datafontcolor', dataratio: '@dataratio', dataweight: '@dataweight', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { console.log("datafontcolor :", $scope.datafontcolor); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._textSlide = []; $scope._gettextslide = function() { $scope._textslide_data = []; GAEAPI.get('web/home', {}).then(function(res) { if (res.ok == 1) { $scope._textSlide = res.data.textslide_banner; var a = $interval(function() { if ($scope._uniqueKey != '') { $interval.cancel(a); $scope.mkCarouselTwo(); } }, 1000); } }); }; $scope._gettextslide(); $scope.mkCarousel1 = function(elem) { setTimeout(function() { var carousel = $('.' + elem); var is_dark; carousel.not('.slick-initialized').slick({ autoplay: false, slidesToShow: 1, dots: true }).addClass('active'); }, 1000); }; $scope.mkCarouselTwo = function() { var carousel = $('.text_slider_container[data-id=' + $scope._key() + ']'); carousel.css('height', '0'); carousel.css('opacity', '0'); setTimeout(function() { carousel.not('.slick-initialized').slick({ dots: true, autoplay: true, autoplaySpeed: 6000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }).closest('section').addClass('active'); carousel.css('height', 'auto'); carousel.css('opacity', '1'); }, 1000); }; $scope._ratio = []; $scope._weight = []; $scope.$watch('dataratio', function(newValue, oldValue) { if (!newValue) { return; } $scope._ratio = newValue.toString().split(","); }); $scope.$watch('dataweight', function(newValue, oldValue) { if (!newValue) { return; } $scope._weight = newValue.toString().split(","); }); $scope.$watch('datafontcolor', function(newValue, oldValue) { if (!newValue) { return; } $scope._color = newValue.toString().split(","); }); $scope.getRatio = function(n) { if (typeof $scope._ratio[n] !== 'undefined' && $scope._ratio[n] != '') { return $scope._ratio[n]; } return '0.7'; }; $scope.getWeight = function(n) { if (typeof $scope._weight[n] !== 'undefined' && $scope._weight[n] != '') { return $scope._weight[n]; } }; $scope.getColor = function(n) { if (typeof $scope._color[n] !== 'undefined' && $scope._color[n] != '') { return $scope._color[n]; } }; }; return promise; });_ui_share_app.directive('componentTextSlideB', function ($rootScope, $routeParams) { var templateName = 'componentTextSlideB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', datafontcolor :'@datafontcolor', dataratio:'@dataratio', dataweight:'@dataweight', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { console.log("datafontcolor :", $scope.datafontcolor); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._textSlide = []; $scope._gettextslide = function(){ $scope._textslide_data = []; GAEAPI.get('web/home',{}).then(function(res){ if(res.ok == 1){ $scope._textSlide = res.data.textslide_banner; var a = $interval(function(){ if($scope._uniqueKey != ''){ $interval.cancel(a); $scope.mkCarouselTwo(); } },1000); } }); }; $scope._gettextslide(); $scope.mkCarousel1 = function(elem){ setTimeout(function(){ var carousel = $('.' + elem); var is_dark; carousel.not('.slick-initialized').slick({ autoplay:false, slidesToShow:1, }).addClass('active'); }, 1000); }; $scope.mkCarouselTwo = function(){ $('.text_slider_container[data-id='+$scope._key()+']').not('.slick-initialized').slick({ autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }).closest('section').addClass('active'); }; $scope._ratio = []; $scope._weight = []; $scope.$watch('dataratio',function(newValue, oldValue){ if(!newValue){ return; } $scope._ratio = newValue.toString().split(","); }); $scope.$watch('dataweight',function(newValue, oldValue){ if(!newValue){ return; } $scope._weight = newValue.toString().split(","); }); $scope.$watch('datafontcolor',function(newValue, oldValue){ if(!newValue){ return; } $scope._color = newValue.toString().split(","); }); $scope.getRatio = function(n){ if(typeof $scope._ratio[n] !== 'undefined' && $scope._ratio[n] !=''){ return $scope._ratio[n]; } return '0.7'; }; $scope.getWeight = function(n){ if(typeof $scope._weight[n] !== 'undefined' && $scope._weight[n] !=''){ return $scope._weight[n]; } }; $scope.getColor = function(n){ if(typeof $scope._color[n] !== 'undefined' && $scope._color[n] !=''){ return $scope._color[n]; } }; }; return promise; }); _ui_share_app.directive('componentTextSlideC', function($rootScope, $routeParams) { var templateName = 'componentTextSlideC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', datafontcolor: '@datafontcolor', dataratio: '@dataratio', dataweight: '@dataweight', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { console.log("datafontcolor :", $scope.datafontcolor); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._textSlide = []; $scope._gettextslide = function() { $scope._textslide_data = []; GAEAPI.get('web/home', {}).then(function(res) { if (res.ok == 1) { $scope._textSlide = res.data.textslide_banner; var a = $interval(function() { if ($scope._uniqueKey != '') { $interval.cancel(a); $scope.mkCarouselTwo(); } }, 1000); } }); }; $scope.mkCarousel1 = function(elem) { setTimeout(function() { var carousel = $('.' + elem); var is_dark; carousel.not('.slick-initialized').slick({ autoplay: false, slidesToShow: 1, }).addClass('active'); }, 1000); }; $scope.mkCarouselTwo = function() { $('.text_slider_container[data-id=' + $scope._key() + ']').not('.slick-initialized').slick({ autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, arrows: false, infinite: true, speed: 600, }).closest('section').addClass('active'); }; $scope._gettextslide(); $scope._ratio = []; $scope._weight = []; $scope.$watch('dataratio', function(newValue, oldValue) { if (!newValue) { return; } $scope._ratio = newValue.toString().split(","); }); $scope.$watch('dataweight', function(newValue, oldValue) { if (!newValue) { return; } $scope._weight = newValue.toString().split(","); }); $scope.$watch('datafontcolor', function(newValue, oldValue) { if (!newValue) { return; } $scope._color = newValue.toString().split(","); }); $scope.getRatio = function(n) { if (typeof $scope._ratio[n] !== 'undefined' && $scope._ratio[n] != '') { return $scope._ratio[n]; } return '0.7'; }; $scope.getWeight = function(n) { if (typeof $scope._weight[n] !== 'undefined' && $scope._weight[n] != '') { return $scope._weight[n]; } }; $scope.getColor = function(n) { if (typeof $scope._color[n] !== 'undefined' && $scope._color[n] != '') { return $scope._color[n]; } }; }; return promise; });_ui_share_app.directive('componentTextSlideE', function($rootScope, $routeParams) { var templateName = 'componentTextSlideE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', datafontcolor: '@datafontcolor', dataratio: '@dataratio', dataweight: '@dataweight', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { console.log("datafontcolor :", $scope.datafontcolor); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._textSlide = []; $scope._gettextslide = function() { $scope._textslide_data = []; GAEAPI.get('web/home', {}).then(function(res) { if (res.ok == 1) { $scope._textSlide = res.data.textslide_banner; var a = $interval(function() { if ($scope._uniqueKey != '') { $interval.cancel(a); $scope.mkCarouselTwo(); } }, 1000); } }); }; $scope._gettextslide(); $scope.mkCarousel1 = function(elem) { setTimeout(function() { var carousel = $('.' + elem); var is_dark; carousel.not('.slick-initialized').slick({ autoplay: false, slidesToShow: 1, dots: true }).addClass('active'); }, 1000); }; $scope.mkCarouselTwo = function() { var carousel = $('.text_slider_container[data-id=' + $scope._key() + ']'); carousel.css('height', '0'); carousel.css('opacity', '0'); setTimeout(function() { carousel.not('.slick-initialized').slick({ dots: true, autoplay: true, autoplaySpeed: 6000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }).closest('section').addClass('active'); carousel.css('height', 'auto'); carousel.css('opacity', '1'); }, 1000); }; $scope._ratio = []; $scope._weight = []; $scope.$watch('dataratio', function(newValue, oldValue) { if (!newValue) { return; } $scope._ratio = newValue.toString().split(","); }); $scope.$watch('dataweight', function(newValue, oldValue) { if (!newValue) { return; } $scope._weight = newValue.toString().split(","); }); $scope.$watch('datafontcolor', function(newValue, oldValue) { if (!newValue) { return; } $scope._color = newValue.toString().split(","); }); $scope.getRatio = function(n) { if (typeof $scope._ratio[n] !== 'undefined' && $scope._ratio[n] != '') { return $scope._ratio[n]; } return '0.7'; }; $scope.getWeight = function(n) { if (typeof $scope._weight[n] !== 'undefined' && $scope._weight[n] != '') { return $scope._weight[n]; } }; $scope.getColor = function(n) { if (typeof $scope._color[n] !== 'undefined' && $scope._color[n] != '') { return $scope._color[n]; } }; }; return promise; });_ui_share_app.directive('componentTextSlideF', function($rootScope, $routeParams) { var templateName = 'componentTextSlideF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', datafontcolor: '@datafontcolor', dataratio: '@dataratio', dataweight: '@dataweight', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { console.log("datafontcolor :", $scope.datafontcolor); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._textSlide = []; $scope._gettextslide = function() { $scope._textslide_data = []; GAEAPI.get('web/home', {}).then(function(res) { if (res.ok == 1) { $scope._textSlide = res.data.textslide_banner; var a = $interval(function() { if ($scope._uniqueKey != '') { $interval.cancel(a); $scope.mkCarouselTwo(); } }, 1000); } }); }; $scope._gettextslide(); $scope.mkCarousel1 = function(elem) { setTimeout(function() { var carousel = $('.' + elem); var is_dark; carousel.not('.slick-initialized').slick({ autoplay: false, slidesToShow: 1, dots: true }).addClass('active'); }, 1000); }; $scope.mkCarouselTwo = function() { var carousel = $('.text_slider_container[data-id=' + $scope._key() + ']'); carousel.css('height', '0'); carousel.css('opacity', '0'); setTimeout(function() { carousel.not('.slick-initialized').slick({ dots: false, autoplay: true, autoplaySpeed: 6000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }).closest('section').addClass('active'); carousel.css('height', 'auto'); carousel.css('opacity', '1'); }, 1000); }; $scope._ratio = []; $scope._weight = []; $scope.$watch('dataratio', function(newValue, oldValue) { if (!newValue) { return; } $scope._ratio = newValue.toString().split(","); }); $scope.$watch('dataweight', function(newValue, oldValue) { if (!newValue) { return; } $scope._weight = newValue.toString().split(","); }); $scope.$watch('datafontcolor', function(newValue, oldValue) { if (!newValue) { return; } $scope._color = newValue.toString().split(","); }); $scope.getRatio = function(n) { if (typeof $scope._ratio[n] !== 'undefined' && $scope._ratio[n] != '') { return $scope._ratio[n]; } return '0.7'; }; $scope.getWeight = function(n) { if (typeof $scope._weight[n] !== 'undefined' && $scope._weight[n] != '') { return $scope._weight[n]; } }; $scope.getColor = function(n) { if (typeof $scope._color[n] !== 'undefined' && $scope._color[n] != '') { return $scope._color[n]; } }; }; return promise; });_ui_share_app.directive('componentTextSlideG', function($rootScope, $routeParams, sliderProvider) { var templateName = 'componentTextSlideG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', margin: '@margin', datafontcolor: '@datafontcolor', dataratio: '@dataratio', dataweight: '@dataweight', callback: '@callback', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window, $http) { console.log("datafontcolor :", $scope.datafontcolor); $scope.currentShopId = parseInt(CUR_THEME.shop_id()); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.isData = false; $scope._textSlide = []; $scope._gettextslide = function() { $scope._textslide_data = []; var shopInt = parseInt(CUR_THEME.shop_id()); GAEAPI.get('web/home', {}).then(function(res) { if (res.ok == 1) { $scope._textSlide = res.data.textslide_banner; $scope.isData = true; if (!$scope._textSlide.banner_array.length && typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope._textSlide.banner_array = [{ 'banner_header': 'An intro text in text slide 1', 'banner_sub_header': 'Text in the middle of slide 1', 'banner_footer': 'Bottom text slide 1' }, { 'banner_header': 'An intro text in text slide 2', 'banner_sub_header': 'Text in the middle of slide 2', 'banner_footer': 'Bottom text slide 2' }, ]; } /*var a = $interval(function(){ if($scope._uniqueKey != ''){ $interval.cancel(a); $scope.mkCarouselTwo(); } },1000);*/ } }); }; $scope._gettextslide(); $scope.mkCarousel1 = function(elem) { setTimeout(function() { var carousel = $('.' + elem); var is_dark; carousel.not('.slick-initialized').slick({ autoplay: false, slidesToShow: 1, dots: true }).addClass('active'); }, 1000); }; $scope.mkCarouselTwo = function() { $('.text_slider_container[data-id=' + $scope._key() + ']').slick({ dots: true, autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }); }; $scope._ratio = []; $scope._weight = []; $scope.$watch('dataratio', function(newValue, oldValue) { if (!newValue) { return; } $scope._ratio = newValue.toString().split(","); }); $scope.$watch('datafontcolor', function(newValue, oldValue) { if (!newValue) { return; } $scope._fontcolor = newValue.toString().split(","); }); $scope.$watch('dataweight', function(newValue, oldValue) { if (!newValue) { return; } $scope._weight = newValue.toString().split(","); }); $scope.getRatio = function(n) { if (typeof $scope._ratio == 'undefined') { return } if (typeof $scope._ratio[n] !== 'undefined' && $scope._ratio[n] != '') { return $scope._ratio[n]; } return '0.7'; }; $scope.getFontcolor = function(n) { if (typeof $scope._fontcolor == 'undefined') { return } if (typeof $scope._fontcolor[n] !== 'undefined' && $scope._fontcolor[n] != '') { return $scope._fontcolor[n]; } return '#000'; }; $scope.getWeight = function(n) { if (typeof $scope._weight == 'undefined') { return } if (typeof $scope._weight[n] !== 'undefined' && $scope._weight[n] != '') { return $scope._weight[n]; } return 'normal'; }; $scope.style_name = ''; $scope.style = function(shop_name) { var name = shop_name; if (name == 'thaitens') { $scope.style_name = name; } else { $scope.style_name = 'undefined'; } }; $scope.style($scope.name); /* Watch when finish repeat */ $scope.slideReady = false; $rootScope.$on('repeatend', function() { $scope.slideReady = true; }); $scope.sliderTimer = null; $scope.intervalTextSliderCheck = 0; /*if(parseInt(CUR_THEME.shop_id()) == 507){*/ var timeoutTextSliderCheck = 0; var elementName = '.tttttttttttttt'; var configSliderTxt = { dots: true, autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600 }; $scope.intervalTextSliderCheck = $interval(function() { if ($scope.isData) { if ($scope._textSlide.banner_array.length && $(elementName).length) { $interval.cancel($scope.intervalTextSliderCheck); timeoutTextSliderCheck = $timeout(function() { $timeout.cancel(timeoutTextSliderCheck); $(elementName).slick(configSliderTxt); }, 1000); } } }, 500); /*} else { angular.element(window).bind('load', function(){ var timeoutTextSliderCheck = 0; var elementName = '.tttttttttttttt'; var configSliderTxt = { dots: true, autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600 }; $scope.intervalTextSliderCheck = $interval(function(){ if($scope._textSlide.banner_array.length && $(elementName).length){ $interval.cancel($scope.intervalTextSliderCheck); timeoutTextSliderCheck = $timeout(function(){ $timeout.cancel(timeoutTextSliderCheck); $(elementName).slick(configSliderTxt); }, 1000); } },500); }); }*/ }; return promise; }); if (CUR_THEME.shop_id() == 507) {}_ui_share_app.directive('componentTextSlideHalf', function ($rootScope, $routeParams) { var templateName = 'componentTextSlideHalf'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', bgcolor: '@bgcolor', datafontcolor :'@datafontcolor', dataratio:'@dataratio', dataweight:'@dataweight', imageset: '@imageurl', videoset: '@videourl', setheight: '@setheight', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._textSlide = []; $scope._gettextslide = function(){ $scope._textslide_data = []; GAEAPI.get('web/home',{}).then(function(res){ if(res.ok == 1){ $scope._textSlide = res.data.textslide_banner; console.log("bannertext : slide",res); var a = $interval(function(){ if($scope._uniqueKey != ''){ $interval.cancel(a); $scope.mkCarouselTwo(); } },1000); } }); }; $scope._gettextslide(); $scope.mkCarousel1 = function(elem){ setTimeout(function(){ var carousel = $('.' + elem); var is_dark; carousel.not('.slick-initialized').slick({ autoplay:false, slidesToShow:1, dots:true }).addClass('active'); }, 1000); }; $scope.mkCarouselTwo = function(){ $('.text_slider_container[data-id='+$scope._key()+']').not('.slick-initialized').slick({ dots: true, autoplay: true, autoplaySpeed: 3000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, }).closest('section').addClass('active'); }; $scope._ratio = []; $scope._weight = []; $scope._color = []; $scope.$watch('dataratio',function(newValue, oldValue){ if(!newValue){ return; } $scope._ratio = newValue.toString().split(","); }); $scope.$watch('dataweight',function(newValue, oldValue){ if(!newValue){ return; } $scope._weight = newValue.toString().split(","); }); $scope.$watch('datafontcolor',function(newValue, oldValue){ if(!newValue){ return; } $scope._color = newValue.toString().split(","); }); $scope.getRatio = function(n){ if(typeof $scope._ratio[n] !== 'undefined' && $scope._ratio[n] !=''){ return $scope._ratio[n]; } return '0.7'; }; $scope.getWeight = function(n){ if(typeof $scope._weight[n] !== 'undefined' && $scope._weight[n] !=''){ return $scope._weight[n]; } }; $scope.getColor = function(n){ if(typeof $scope._color[n] !== 'undefined' && $scope._color[n] !=''){ return $scope._color[n]; } }; }; return promise; }); _ui_share_app.directive('componentThreeBlock', function ($rootScope, $routeParams) { var templateName = 'componentThreeBlock'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.directive('compomentTwoBlock', function ($rootScope, $routeParams) { var templateName = 'compomentTwoBlock'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { }; return promise; }); _ui_share_app.directive('componentVendorSlide', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentVendorSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', position:'@position', textstyle:'@textstyle', buttonstyle:'@buttonstyle', animatestyle:'@animatestyle', margin:'@margin', font:'@font', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'VendorSlide'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; if(!carouselData.get($scope.type) && !$scope.data.length){ var dataSend = { 'txt_referral_type_id': 18, 'cur_page': 1, 'per_page': 6, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/lists', dataSend, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.dataList; if(resultArray.length){ carouselData.set($scope.type, resultArray); console.log("datatest1232",resultArray); $scope.data = resultArray; } else { $scope.done = true; return; } var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); }); } else { $scope.data = carouselData.get($scope.type); console.log("%ccarouselData => get state","background-color:yellow;color:black;padding:5px;"); var t = $interval(function () { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.initSlider(); }, 300); } }, 500); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, centerMode: true, centerPadding: '0px', slidesToShow: 3, slidesToScroll: 1, dots: false, arrows: false, infinite: true, responsive: [ { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 3 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 1 } } ] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ var a = i; if(a.indexOf('http') == -1){ return 'http://'+i; } return i; }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; }; return promise; }); _ui_share_app.directive('componentVendorTypeA', function ($rootScope, $routeParams) { var templateName = 'componentVendorTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.vendorList = []; $scope.getVendorList = function() { var dataSend = { 'txt_referral_type_id': 18, 'cur_page': 1, 'per_page': 6, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.vendorList = res.data.dataList; console.log("getVendorList",$scope.vendorList); } }); } $scope.getVendorList(); }; return promise; }); var $inverificationPopupTypeCct = { path: CUR_THEME.devsource_url() + "dev.sugarfree/share/componentVerificationTypeCct/", icnPath: CUR_THEME.extensions_url() + "../../assets/", templateRoot: "root.php", api: GURL.base_api_url(), }; $inverificationPopupTypeCct.install = function(shopId, customBuild) { $.get($inverificationPopupTypeCct.path + 'componentVerificationTypeCct.css', function(response) { $('head').append(''); }); $.get($inverificationPopupTypeCct.path + 'root.php', { imgpath: $inverificationPopupTypeCct.icnPath, shopId: shopId, custom: customBuild, path: $inverificationPopupTypeCct.path }, function(response) { $('body').append(response); }); }; $inverificationPopupTypeCct.display = function() { var display = { consoleLog: function(statu, data) { var statuConsole = true; if (statuConsole) { console.log(statu, data); } }, contronlClass: function(class_in, array_in) { $(class_in).css(array_in); }, addClass: function(class_in, status) { var class_add = $(class_in); if (!class_add.hasClass(status)) { class_add.addClass(status); } }, removeClass: function(class_in, status) { var class_remove = $(class_in); if (class_remove.hasClass(status)) { class_remove.removeClass(status); } }, getVal: function(class_or_id) { var get_val = $(class_or_id).val(); return get_val; }, setCss: function(class_in, styleOne, styleTwo) { $(class_in).css(styleOne, styleTwo); }, setVal: function(class_in, val) { $(class_in).val(val); }, reset: function() { $inverificationPopupTypeCct.display().setCss("#verification-plantinum-number-vcct", "border", ""); $inverificationPopupTypeCct.display().setVal("#verification-plantinum-number-vcct", ""); $inverificationPopupTypeCct.display().setCss("#verification-error-plantinum-number-vcct", "opacity", 0); $inverificationPopupTypeCct.display().setCss("#verification-pin-vcct", "border", ""); $inverificationPopupTypeCct.display().setVal("#verification-pin-vcct", ""); $inverificationPopupTypeCct.display().setCss("#verification-error-pin-vcct", "opacity", 0); }, }; return display; }; $inverificationPopupTypeCct.api = function() { var api = { checkOk: function(data, callback) { var check_ok = false; if (data.ok == 1) { check_ok = true; } callback(check_ok); }, validatecodeCheck: function(ket, code, callback) { var dataSend = { 'txt_key_code': ket, 'txt_pass_code': code, }; $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : validatecodeCheck : dataSend : ", dataSend); UiCustomerBox.api.post("validatecode/check", dataSend).then(function(output) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : validatecodeCheck : output : ", output); $inverificationPopupTypeCct.api().checkOk(output, function(check_ok) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : checkOk : check_ok : ", check_ok); if (check_ok) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : check_ok : ", "OK"); } else { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : api : check_ok : ", "ERROR"); } callback(check_ok); }); }); }, }; return api; }; $inverificationPopupTypeCct.check = function() { var check = { checkFormat: function(class_or_id, isFunction, callback) { var form_in = $inregisterPopupTypeCct.display().getVal(class_or_id); $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : form : ", form_in); var check_format = false; var check_alert = ""; if (isFunction == 'length') { $inregisterPopupTypeCct.check().isLength(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isLength : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isLength : status_check : ", "ERROR"); check_alert = "กรุณากรอก" } }); } else if (isFunction == 'select') { $inregisterPopupTypeCct.check().isSelect(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isSelect : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isSelect : status_check : ", "ERROR"); check_alert = "กรุณาเลือก" } }); } else if (isFunction == 'email') { $inregisterPopupTypeCct.check().isEmail(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isEmail : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isEmail : status_check : ", "ERROR"); check_alert = "ตรวจสอบรูปแบบ" } }); } else if (isFunction == 'mobile') { $inregisterPopupTypeCct.check().isMobile(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isMobile : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isMobile : status_check : ", "ERROR"); check_alert = "ตรวจสอบรูปแบบ" } }); } else if (isFunction == 'password') { $inregisterPopupTypeCct.check().isPassword(form_in, function(status_check) { if (status_check) { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isPassword : status_check : ", "OK"); check_format = true; } else { $inregisterPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : check : checkFormat : isPassword : status_check : ", "ERROR"); check_alert = "ตรวจสอบรูปแบบ" } }); } callback(form_in, check_format, check_alert); }, checkStatusAll: function(data_array, callback) { var check_data_array = data_array; var check_status_all = false; var status_pass = 0; var status_error = 0; if (data_array.length) { for (var i = 0; data_array.length > i; i++) { if (data_array[i].status) { status_pass++; for (var j = 0; data_array[i].class_or_id.length > j; j++) { $inregisterPopupTypeCct.display().formPass(data_array[i].class_or_id[j]); $inregisterPopupTypeCct.display().removeClass(data_array[i].class_or_id_error[j], "error"); $inverificationPopupTypeCct.display().setCss(data_array[i].class_or_id_error[j], "opacity", 0); $inregisterPopupTypeCct.display().postVal(data_array[i].class_or_id_error[j], ""); } } else { status_error++; for (var j = 0; data_array[i].class_or_id.length > j; j++) { $inregisterPopupTypeCct.display().formError(data_array[i].class_or_id[j]); $inregisterPopupTypeCct.display().addClass(data_array[i].class_or_id_error[j], "error"); $inverificationPopupTypeCct.display().setCss(data_array[i].class_or_id_error[j], "opacity", 1); $inregisterPopupTypeCct.display().postVal(data_array[i].class_or_id_error[j], data_array[i].alert); } } } } if (status_error == 0) { check_status_all = true; } callback(check_data_array, check_status_all); }, isLength: function(form_in, callback) { var status_check = false; if (form_in.length > 1) { status_check = true; } callback(status_check); }, isSelect: function(form_in, callback) { var status_check = false; if (form_in != '0') { status_check = true; } callback(status_check); }, isEmail: function(form_in, callback) { var format_email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var output_check = format_email.test(form_in); var status_check = false; if (output_check) { status_check = true; } callback(status_check); }, isPassword: function(form_in, callback) { var status_check = false; if (form_in.length >= 6) { status_check = true; } callback(status_check); }, isMobile: function(form_in, callback) { var format_email = /^(([0-9]{8,10}))$/; var output_check = format_email.test(form_in); var status_check = false; if (output_check) { status_check = true; } callback(status_check); }, }; return check; }; $inverificationPopupTypeCct.verification = function() { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : verification : ", "verification"); var form_submit = [{ class_or_id: ["#verification-plantinum-number-vcct"], class_or_id_error: ["#verification-error-plantinum-number-vcct"], is_function: "length", var: "", status: "", name: " Plantinum Number", alert: "", }, { class_or_id: ["#verification-pin-vcct"], class_or_id_error: ["#verification-error-pin-vcct"], is_function: "length", var: "", status: "", name: " pin", alert: "", }]; $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : form_submit.length : ", form_submit.length); for (var i = 0; form_submit.length > i; i++) { $inverificationPopupTypeCct.check().checkFormat(form_submit[i].class_or_id[0], form_submit[i].is_function, function(form_in, check_format, check_alert) { $inverificationPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : firstname : checkFormat : form_in : ", form_in); form_submit[i].var = form_in; $inverificationPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : firstname : checkFormat : check_format : ", check_format); form_submit[i].status = check_format; $inverificationPopupTypeCct.display().consoleLog("inregisterPopupTypeCct : submitRegister : firstname : checkFormat : check_alert : ", check_alert); form_submit[i].alert = check_alert + form_submit[i].name; }); } $inverificationPopupTypeCct.check().checkStatusAll(form_submit, function(check_data_array, check_status_all) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : submitRegister : checkStatusAll : check_data_array : ", check_data_array); $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : submitRegister : checkStatusAll : check_status_all : ", check_status_all); $inverificationPopupTypeCct.api().validatecodeCheck(check_data_array[0].var, check_data_array[1].var, function(check_ok) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : verification : check_ok : ", check_ok); if (check_ok) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : verification : check_ok : ", "OK"); $inverificationPopupTypeCct.toRegister(); } else { for (var i = 0; form_submit.length > i; i++) { $inregisterPopupTypeCct.display().formError(form_submit[i].class_or_id[0]); $inregisterPopupTypeCct.display().addClass(form_submit[i].class_or_id_error[0], "error"); $inverificationPopupTypeCct.display().setCss(form_submit[i].class_or_id_error[0], "opacity", 1); var post_text_name = "ไม่พบ " + form_submit[i].name; $inregisterPopupTypeCct.display().postVal(form_submit[i].class_or_id_error[0], post_text_name); } } }); }); }; $inverificationPopupTypeCct.open = function() { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : ", " open"); $inverificationPopupTypeCct.display().reset(); $inverificationPopupTypeCct.display().addClass(".verification_overlay", "is_open"); $inverificationPopupTypeCct.display().contronlClass('html', { 'overflow-y': 'scroll', 'overflow': 'hidden' }); $inverificationPopupTypeCct.display().contronlClass('body', { 'overflow': 'hidden', 'position': 'relative' }); var timeOpen = setTimeout(function() { $inverificationPopupTypeCct.display().addClass(".verification.from_background", "is_open"); }, 100); $(document).keypress(function(output) { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : keypress : output : ", output); var keyCode = (output.keyCode ? output.keyCode : output.which); $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : keypress : keyCode : ", keyCode); if (keyCode == '13') { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : keypress : output : keyCode : ", "ENTER"); $inverificationPopupTypeCct.verification(); } }); }; $inverificationPopupTypeCct.close = function() { $inverificationPopupTypeCct.display().consoleLog("inverificationPopupTypeCct : ", " close"); $inverificationPopupTypeCct.display().removeClass(".verification_overlay", "is_open"); $inverificationPopupTypeCct.display().removeClass(".verification.from_background", "is_open"); $inverificationPopupTypeCct.display().contronlClass('html', { 'overflow-y': 'unset', 'overflow': 'unset' }); $inverificationPopupTypeCct.display().contronlClass('body', { 'overflow': 'auto', 'position': 'relative' }); }; $inverificationPopupTypeCct.toRegister = function() { $inverificationPopupTypeCct.close(); $inregisterPopupTypeCct.open(); }; $inverificationPopupTypeCct.toLogin = function() { $inverificationPopupTypeCct.close(); $inloginPopupTypeCct.open(); }; $inverificationPopupTypeCct.toHome = function() { $inverificationPopupTypeCct.close(); };_ui_share_app.directive('componentVideo', function ($rootScope, $routeParams) { var templateName = 'componentVideo'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ $scope.dataArray = []; GAEAPI.get('shop/current',{},$scope).then(function(e){ if(e.ok == 1){ var t = { 'shop_video_link': e.data.shop_video_link, 'shop_video_embed_code': e.data.shop_video_embed_code, 'shop_video_title': e.data.shop_video_title, 'shop_video_description': e.data.shop_video_description, }; $scope.dataArray.push(t); } }); }; $scope.getData(); $scope.activateOverlayVids = function(code){ if(!$scope.dataArray.length && code !== ""){ return; } angular.element('#zdv447_3').html(code); angular.element('._component_video_sreen_block').addClass('active'); }; $scope.unActiveOverlayVids = function(){ angular.element('#zdv447_3').html(""); angular.element('._component_video_sreen_block').removeClass('active'); }; }; return promise; }); _ui_share_app.directive('componentVideoAb', function ($rootScope, $routeParams) { var templateName = 'componentVideoAb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ $scope.dataArray = []; GAEAPI.get('shop/current',{},$scope).then(function(e){ if(e.ok == 1){ var t = { 'shop_video_link': e.data.shop_video_link, 'shop_video_embed_code': e.data.shop_video_embed_code, 'shop_video_title': e.data.shop_video_title, 'shop_video_description': e.data.shop_video_description, }; $scope.dataArray.push(t); } }); }; $scope.getData(); $scope.activateOverlayVids = function(code){ if(!$scope.dataArray.length && code !== ""){ return; } angular.element('#zdv447_3').html(code); angular.element('._component_video_sreen_block').addClass('active'); }; $scope.unActiveOverlayVids = function(){ angular.element('#zdv447_3').html(""); angular.element('._component_video_sreen_block').removeClass('active'); }; }; return promise; }); _ui_share_app.directive('componentVideoB', function($rootScope, $routeParams) { var templateName = 'componentVideoB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function() { var d = { 'cur_page': 1, 'per_page': 1 }; GAEAPI.get('video/lists', d).then(function(e) { if (e.ok == 1) { $scope.dataArray = e.data.dataList; console.log("video/lists",$scope.dataArray); } }); }; $scope.getData(); $scope.activateOverlayVids = function(code) { if (!$scope.dataArray.length && code !== "") { return; } angular.element('#zdv447_3').html(code); angular.element('._component_video_sreen_block').addClass('active'); }; $scope.unActiveOverlayVids = function() { angular.element('#zdv447_3').html(""); angular.element('._component_video_sreen_block').removeClass('active'); }; }; return promise; });_ui_share_app.directive('componentVideoC', function ($rootScope, $routeParams) { var templateName = 'componentVideoC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ $scope.dataArray = []; GAEAPI.get('shop/current',{},$scope).then(function(e){ if(e.ok == 1){ var t = { 'shop_video_link': e.data.shop_video_link, 'shop_video_embed_code': e.data.shop_video_embed_code, 'shop_video_title': e.data.shop_video_title, 'shop_video_description': e.data.shop_video_description, 'shop_video_image': e.data.shop_video_image[0].image_url, }; $scope.dataArray.push(t); } }); }; $scope.getData(); $scope.activateOverlayVids = function(code){ if(!$scope.dataArray.length && code !== ""){ return; } angular.element('#zdv447_3').html(code); angular.element('._component_video_sreen_block').addClass('active'); document.body.style.overflow = 'hidden'; }; $scope.unActiveOverlayVids = function(){ angular.element('#zdv447_3').html(""); angular.element('._component_video_sreen_block').removeClass('active'); document.body.style.overflow = 'auto'; }; }; return promise; }); _ui_share_app.directive('componentVideoD', function($rootScope, $routeParams) { var templateName = 'componentVideoD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'topic_top': '?topicTop', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function() { $scope.dataArray = []; GAEAPI.get('shop/current', {}, $scope).then(function(e) { if (e.ok == 1) { var t = { 'shop_video_link': e.data.shop_video_link, 'shop_video_embed_code': e.data.shop_video_embed_code, 'shop_video_title': e.data.shop_video_title, 'shop_video_description': e.data.shop_video_description, 'shop_video_image': e.data.shop_video_image[0].image_url, }; $scope.dataArray.push(t); } }); }; $scope.getData(); $scope.activateOverlayVids = function(code) { if (!$scope.dataArray.length && code !== "") { return; } angular.element('#zdv447_3').html(code); angular.element('._component_video_sreen_block').addClass('active'); document.body.style.overflow = 'hidden'; }; $scope.unActiveOverlayVids = function() { angular.element('#zdv447_3').html(""); angular.element('._component_video_sreen_block').removeClass('active'); document.body.style.overflow = 'auto'; }; }; return promise; });_ui_share_app.directive('componentVideoDay', function ($rootScope, $routeParams) { var templateName = 'componentVideoDay'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', videowidth:'@videowidth', videoheight:'@videoheight', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.getTimeNow = []; $scope._getTimeNow = function() { var d = new Date(); var n = d.toDateString(); $scope.getTimeNow = n.split(" "); console.log('Date',Date()); console.log('getTimeNow',$scope.getTimeNow); }; $scope._getTimeNow(); $scope.dataVideo = []; $scope.getVideo = function() { var dataSend = { 'cur_page': 1, 'per_page': 8, }; GAEAPI.get('video/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.dataVideo = res.data.dataList; } console.log("dataVideo",$scope.dataVideo); }); }; $scope.getVideo(); }; return promise; }); _ui_share_app.directive('componentVideoDb', function ($rootScope, $routeParams) { var templateName = 'componentVideoDb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', size: '@size' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.getData = function(){ $scope.dataArray = []; GAEAPI.get('shop/current',{},$scope).then(function(e){ if(e.ok == 1){ var t = { 'shop_video_link': e.data.shop_video_link, 'shop_video_embed_code': e.data.shop_video_embed_code, 'shop_video_title': e.data.shop_video_title, 'shop_video_description': e.data.shop_video_description, 'shop_video_image': e.data.shop_video_image[0].image_url, }; $scope.dataArray.push(t); } }); }; $scope.getData(); $scope.activateOverlayVids = function(code){ if(!$scope.dataArray.length && code !== ""){ return; } angular.element('#zdv447_3').html(code); angular.element('._component_video_sreen_block').addClass('active'); document.body.style.overflow = 'hidden'; }; $scope.unActiveOverlayVids = function(){ angular.element('#zdv447_3').html(""); angular.element('._component_video_sreen_block').removeClass('active'); document.body.style.overflow = 'auto'; }; }; return promise; }); _ui_share_app.directive('componentVideoDetail', function ($rootScope, $routeParams) { var templateName = 'componentVideoDetail'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._param = $routeParams.video_id; console.log("eyreyhfdsf :", $scope._param); $scope.$watch('_param', function(newValue, oldValue) { if (newValue) { $scope.getData(newValue); } }); $scope.dataArray = false; $scope.getData = function(video_id){ console.log("eyreyhfdsf 1:", video_id); $scope.dataArray = false; var d = { 'txt_video_id': video_id, }; GAEAPI.get('video/id',d,$scope).then(function(e){ if(e.ok == 1){ $scope.dataArray = e.data; console.log("eyreyhfdsf :", $scope.dataArray); } }); }; $scope.activateOverlayVids = function(code){ if(!$scope.dataArray.length && code !== ""){ return; } angular.element('#zdv447_3').html(code); angular.element('._component_video_sreen_block').addClass('active'); }; $scope.unActiveOverlayVids = function(){ angular.element('#zdv447_3').html(""); angular.element('._component_video_sreen_block').removeClass('active'); }; }; return promise; }); _ui_share_app.directive('componentVideoDetailB', function ($rootScope, $routeParams) { var templateName = 'componentVideoDetailB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._param = $routeParams.video_id; console.log("eyreyhfdsf :", $scope._param); $scope.$watch('_param', function(newValue, oldValue) { if (newValue) { $scope.getData(newValue); } }); $scope.dataArray = false; $scope.getData = function(video_id){ console.log("eyreyhfdsf 1:", video_id); $scope.dataArray = false; var d = { 'txt_video_id': video_id, }; GAEAPI.get('video/id',d,$scope).then(function(e){ if(e.ok == 1){ $scope.dataArray = e.data; console.log("eyreyhfdsf :", $scope.dataArray); } }); }; $scope.activateOverlayVids = function(code){ if(!$scope.dataArray.length && code !== ""){ return; } angular.element('#zdv447_3').html(code); angular.element('._component_video_sreen_block').addClass('active'); }; $scope.unActiveOverlayVids = function(){ angular.element('#zdv447_3').html(""); angular.element('._component_video_sreen_block').removeClass('active'); }; }; return promise; }); _ui_share_app.factory('$componentVideoList', function componentVideoList($routeParams, $timeout) { return });_ui_share_app.directive('componentVideoListA', function($rootScope, $routeParams, $location) { var templateName = 'componentVideoListA'; var componentMain = 'componentVideoList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'name': '@name', 'datafontcolor': '@datafontcolor', 'margin': '@margin', 'column': '@column', 'maxresult': '@maxresult', 'morebutton': '@morebutton', 'headtext': '@headtext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.datalength = null; $scope._datafontcolor = (typeof $scope.datafontcolor == 'undefined' || $scope.datafontcolor == '') ? 'primary_text' : $scope.datafontcolor; $scope.data = []; var maxresult = $scope.maxresult; $scope.fetchTimes = 1; $scope.fetchLoad = false; $scope.loadMoreButton = false; $scope._dataArrayState = { load: false, done: false }; $scope.getData = function() { $scope._dataArrayState = $scope.StateData(true, false); $scope.fetchLoad = true; if (typeof $scope.maxresult !== 'undefined' && $scope.maxresult !== '') { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': maxresult, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } else { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': 18, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } GAEAPI.get('video/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { console.log("video/lists :", e.data); $scope.datalength = e.data.total_rows; if (!$scope.data.length) { $scope.data = e.data.dataList; console.log("data 123123: 0", $scope.data); } else { var currentData = $scope.data; $scope.data = currentData.concat(e.data.dataList); console.log("data 123123: 1", $scope.data); } } $scope._dataArrayState = $scope.StateData(false, true); $scope.fetchTimes++; $scope.fetchLoad = false; /* If viddeo-lists page => show load more button */ if ($location.path().indexOf('video-lists') !== -1) { $scope.loadMoreButton = true; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getData(); $scope.doLoadMore = function() { return $scope.getData(); }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object) { $('#video-player').html(''); if (object.video_embed_code !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.location.href = object.video_link; } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.showDebug = function() { return (typeof $routeParams.debugvideo !== 'undefined') ? true : false; }; $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; }; return promise; });_ui_share_app.directive('componentVideoListAb', function($rootScope, $routeParams, $location) { var templateName = 'componentVideoListAb'; var componentMain = 'componentVideoList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'name':'@name', 'margin': '@margin', 'column': '@column', 'maxresult': '@maxresult', 'morebutton': '@morebutton', 'headtext': '@headtext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.datalength = null; $scope.data = []; var maxresult = $scope.maxresult; $scope.fetchTimes = 1; $scope.fetchLoad = false; $scope.loadMoreButton = false; $scope._dataArrayState = { load: true, done: false }; $scope.getData = function() { // $scope._dataArrayState = $scope.StateData(true, false); $scope.fetchLoad = true; if (typeof $scope.maxresult !== 'undefined' && $scope.maxresult !== '') { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': maxresult, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } else { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': 18, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } GAEAPI.get('video/lists', dataSend , $scope).then(function(e) { if (e.ok == 1) { console.log("video/lists :", e.data); $scope.datalength = e.data.total_rows; if (!$scope.data.length) { $scope.data = e.data.dataList; console.log("data 123123: 0", $scope.data); } else { var currentData = $scope.data; $scope.data = currentData.concat(e.data.dataList); console.log("data 123123: 1", $scope.data); } } $scope._dataArrayState = $scope.StateData(false, true); $scope.fetchTimes++; $scope.fetchLoad = false; /* If viddeo-lists page => show load more button */ if ($location.path().indexOf('video-lists') !== -1) { $scope.loadMoreButton = true; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getData(); $scope.doLoadMore = function() { return $scope.getData(); }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object) { $('#video-player').html(''); if (object.video_embed_code !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.location.href = object.video_link; } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.showDebug = function() { return (typeof $routeParams.debugvideo !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentVideoListAc', function($rootScope, $routeParams, $location) { var templateName = 'componentVideoListAc'; var componentMain = 'componentVideoList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'name': '@name', 'datafontcolor': '@datafontcolor', 'margin': '@margin', 'column': '@column', 'maxresult': '@maxresult', 'morebutton': '@morebutton', 'headtext': '@headtext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.datalength = null; $scope._datafontcolor = (typeof $scope.datafontcolor == 'undefined' || $scope.datafontcolor == '') ? 'primary_text' : $scope.datafontcolor; $scope.data = []; var maxresult = $scope.maxresult; $scope.fetchTimes = 1; $scope.fetchLoad = false; $scope.loadMoreButton = false; $scope._dataArrayState = { load: false, done: false }; $scope.getData = function() { $scope._dataArrayState = $scope.StateData(true, false); $scope.fetchLoad = true; if (typeof $scope.maxresult !== 'undefined' && $scope.maxresult !== '') { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': maxresult, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } else { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': 18, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } GAEAPI.get('video/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { console.log("video/lists :", e.data); $scope.datalength = e.data.total_rows; if (!$scope.data.length) { $scope.data = e.data.dataList; console.log("data 123123: 0", $scope.data); } else { var currentData = $scope.data; $scope.data = currentData.concat(e.data.dataList); console.log("data 123123: 1", $scope.data); } } $scope._dataArrayState = $scope.StateData(false, true); $scope.fetchTimes++; $scope.fetchLoad = false; /* If viddeo-lists page => show load more button */ if ($location.path().indexOf('video-lists') !== -1) { $scope.loadMoreButton = true; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getData(); $scope.doLoadMore = function() { return $scope.getData(); }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object) { $('#video-player').html(''); if (object.video_embed_code !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.location.href = object.video_link; } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.showDebug = function() { return (typeof $routeParams.debugvideo !== 'undefined') ? true : false; }; $scope.viewOptimizeImage = function(size, image_url, image_width) { if (window.devicePixelRatio >= 2 || parseInt(image_width) <= size) { return image_url; } var a = image_url.split("/"), b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; }; return promise; });_ui_share_app.directive('componentVideoListAd', function($rootScope, $routeParams, $location) { var templateName = 'componentVideoListAd'; var componentMain = 'componentVideoList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', type: '@type', limit: '@limit', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = { name: "componentVideoListAd", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._margin = ($scope.margin != undefined && $scope.margin != "") ? { margin: $scope.margin } : { margin: 0 }; $scope._limit = ($scope.limit != undefined && $scope.limit != "") ? parseInt($scope.limit) : 1; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, main: function() { var _self = this; } } return getFunction; }; $scope.control = function() { var getFunction = { popupVideo: function(state, video_link, video_embed_code) { var _self = this; if (video_embed_code != '') { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } else if (video_link != '') { window.open(video_link, '_blank'); } else { $scope.data_control.page_video.popup = state; $scope.data_control.page_video.shop_video_embed_code = video_embed_code; } }, main: function() { var _self = this; } } return getFunction; }; $scope.data_control = { page_video: { popup: false, shop_video_embed_code: "" } } /* get api */ $scope.data_api = { load_more: { load: false, cur_page: 1, per_page: $scope._limit, total_rows: 0 }, video: { data_send: {}, api: "video/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.loadMore = function() { if (!$scope.data_api.load_more.load) { $scope.data_api.load_more.cur_page++; $scope.data_api.load_more.load = true; $scope.getData().getRouteParams(function(_self, params, state) { _self.formatDataSend($scope.data_api.video, function(res_data) { var filter_json = { 'badge_id_array': [18] }; var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var oldData = res_data.data_array; res_data.data_array = oldData.concat(res_api.data.dataList); $scope.data_api.load_more.total_rows = res_api.data.total_rows; } else { $scope.data_api.load_more.cur_page--; } $scope.data_api.load_more.load = false; }); }); }); }); } } $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.video.data_array_state = state; _self.formatDataSend($scope.data_api.video, function(res_data) { var filter_json = { 'badge_id_array': [18] }; var dataSend = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify(filter_json) }; res_data.data_send = dataSend; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; }); }); }); }); /* get api */ }; return promise; });_ui_share_app.directive('componentVideoListB', function($rootScope, $routeParams, $location) { var templateName = 'componentVideoListB'; var componentMain = 'componentVideoList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'margin': '@margin', 'column': '@column', 'maxresult': '@maxresult', 'morebutton': '@morebutton', 'headtext': '@headtext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.data = []; $scope.dataState = { load: false, done: false }; }; return promise; });_ui_share_app.directive('componentVideoListC', function($rootScope, $routeParams, $location) { var templateName = 'componentVideoListC'; var componentMain = 'componentVideoList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'margin': '@margin', 'column': '@column', 'maxresult': '@maxresult', 'morebutton': '@morebutton', 'headtext': '@headtext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.datalength = null; $scope.data = []; var maxresult = $scope.maxresult; $scope.fetchTimes = 1; $scope.fetchLoad = false; $scope.loadMoreButton = false; $scope.getData = function() { $scope.fetchLoad = true; if (typeof maxresult !== 'undefined' && maxresult !== '') { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': maxresult, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } else { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': 18, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } GAEAPI.get('video/lists', dataSend).then(function(e) { if (e.ok == 1) { console.log("video/lists :", e.data); $scope.datalength = e.data.total_rows; if (!$scope.data.length) { $scope.data = e.data.dataList; console.log("data 123123: 0",$scope.data); } else { var currentData = $scope.data; $scope.data = currentData.concat(e.data.dataList); console.log("data 123123: 1",$scope.data); } } $scope.fetchTimes++; $scope.fetchLoad = false; /* If viddeo-lists page => show load more button */ if ($location.path().indexOf('video-lists') !== -1) { $scope.loadMoreButton = true; } }); }; $scope.getData(); $scope.doLoadMore = function() { return $scope.getData(); }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object) { $('#video-player').html(''); if (object.video_embed_code !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.location.href = object.video_link; } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.showDebug = function() { return (typeof $routeParams.debugvideo !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentVideoListImage', function($rootScope, $routeParams, $location) { var templateName = 'componentVideoListImage'; var componentMain = 'componentVideoList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'datafontcolor': '@datafontcolor', 'margin': '@margin', 'column': '@column', 'maxresult': '@maxresult', 'morebutton': '@morebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.datalength = null; $scope._datafontcolor = (typeof $scope.datafontcolor == 'undefined' || $scope.datafontcolor == '') ? 'primary_text' : $scope.datafontcolor; $scope.data = []; var maxresult = $scope.maxresult; $scope.fetchTimes = 1; $scope.fetchLoad = false; $scope.loadMoreButton = false; $scope._dataArrayState = { load: false, done: false }; $scope.getData = function() { $scope._dataArrayState = $scope.StateData(true, false); $scope.fetchLoad = true; if (typeof $scope.maxresult !== 'undefined' && $scope.maxresult !== '') { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': maxresult, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } else { var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': 18, 'txt_sortby': 'video_sort_index_0-9', 'txt_filter_json': JSON.stringify({ 'badge_id_array': [18] }) }; } GAEAPI.get('video/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { console.log("video/lists :", e.data); $scope.datalength = e.data.total_rows; if (!$scope.data.length) { $scope.data = e.data.dataList; console.log("data 123123: 0", $scope.data); } else { var currentData = $scope.data; $scope.data = currentData.concat(e.data.dataList); console.log("data 123123: 1", $scope.data); } } $scope._dataArrayState = $scope.StateData(false, true); $scope.fetchTimes++; $scope.fetchLoad = false; /* If viddeo-lists page => show load more button */ if ($location.path().indexOf('video-lists') !== -1) { $scope.loadMoreButton = true; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getData(); $scope.doLoadMore = function() { return $scope.getData(); }; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object) { $('#video-player').html(''); if (object.video_embed_code !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.location.href = object.video_link; } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.showDebug = function() { return (typeof $routeParams.debugvideo !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentVideoSlide', function ($rootScope, $routeParams, sliderProvider, carouselData) { var templateName = 'componentVideoSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { size:'@size', position:'@position', textstyle:'@textstyle', buttonstyle:'@buttonstyle', animatestyle:'@animatestyle', margin:'@margin', font:'@font', imgpath:'@imgpath', }; /*promise.link = function (scope, element, attr) {};*/ promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.data = []; $scope.type = 'VideoSlide'; $scope.assetsPath = 'extensions/themes/assets/'; $scope.done = false; if(!carouselData.get($scope.type) && !$scope.data.length){ var dataSend = { 'cur_page': 1, 'per_page': 20, 'badge_id_array':[18], }; GAEAPI.get('video/lists', dataSend, $scope).then(function (res) { if(res.ok != 1){ return; } var resultArray = res.data.dataList; if(resultArray.length){ carouselData.set($scope.type, resultArray); console.log("datatest1232",resultArray); $scope.data = resultArray; } else { $scope.done = true; return; } var t = $interval(function () { if ($scope._uniqueKey !== "" && $scope.imageSize() > 0) { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.done = true; $scope.initSlider(); }, 300); } }, 500); }); } else { $scope.data = carouselData.get($scope.type); console.log("%ccarouselData => get state","background-color:yellow;color:black;padding:5px;"); var t = $interval(function () { if ($scope._uniqueKey !== "") { $interval.cancel(t); var tt = $timeout(function () { $timeout.cancel(tt); $scope.initSlider(); }, 300); } }, 500); } /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.imageSize = function(){ return angular.element("img.image_lazy_loaded").length; }; $scope.initSlider = function(){ var elementName = '.component_carousel_map[data-id="'+$scope._key()+'"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, centerMode: true, centerPadding: '0px', slidesToShow: 3, slidesToScroll: 1, dots: false, arrows: false, infinite: true, responsive: [ { breakpoint: 768, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 1 } }, { breakpoint: 480, settings: { arrows: false, centerMode: true, centerPadding: '0px', slidesToShow: 1 } } ] }; var extraOptions = { animate: false }; sliderProvider(elementName, optionsParmas, $scope.type, $scope._key(), extraOptions); }; $scope.checkHide = function(){ var r = false; if(angular.element('.component_carousel_map.slick-initialized[data-id="'+$scope._key()+'"]').length){ r = true; } return r; }; $scope.viewLink = function(i){ var a = i; if(a.indexOf('http') == -1){ return 'http://'+i; } return i; }; $scope.video_link_play = ""; $scope.set_video_play = function(video_id){ $scope.video_link_play = ""; var dataSend = { 'txt_video_id': video_id, }; GAEAPI.get('video/id', dataSend, $scope).then(function (res) { if(res.ok == 1){ $scope.video_link_play = res.data; $('#set_video').show(); $('body').css("overflow","hidden"); } }); }; $scope.closeVideo = function(){ $('#set_video').hide(); $('body').css("overflow","auto"); }; $scope.slickGoLeft=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight=function(){ setTimeout(function () { $('.component_carousel_map[data-id="'+$scope._key()+'"]').slick('slickNext'); }, 100); }; }; return promise; }); _ui_share_app.factory('$componentVideosList', function componentVideosList($routeParams, $timeout) { return });_ui_share_app.directive('componentVideosListCardA', function($rootScope, $routeParams) { var templateName = 'componentVideosListCardA'; var componentMain = 'componentVideosList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '=datain', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object) { $('#video-player').html(''); if (object.video_embed_code !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.open(object.video_link, '_blank'); } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentVideosListCardAa', function($rootScope, $routeParams) { var templateName = 'componentVideosListCardAa'; var componentMain = 'componentVideosList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '=datain', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object) { $('#video-player').html(''); if (object.video_embed_code !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.open(object.video_link, '_blank'); } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentVideosListCardB', function($rootScope, $routeParams) { var templateName = 'componentVideosListCardB'; var componentMain = 'componentVideosList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '=datain', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object) { $('#video-player').html(''); if (object.video_embed_code !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.open(object.video_link, '_blank'); } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(''); $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentVideosListCardC', function($rootScope, $routeParams) { var templateName = 'componentVideosListCardC'; var componentMain = 'componentVideosList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { datashow: '=datain', stylebutton: '@stylebutton', dataview: '@dataview', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.diplay = function() { var diplay = { diplayHtml: function(class_and_id, data) { $(class_and_id).html(data); }, clickVideo: function(object) { $scope.diplay().diplayHtml("#video-player", ""); if (object.video_embed_code != "") { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else { return window.open(object.video_link, '_blank'); } }, consoleLog: function(statu_in, data_in) { var statu = true; if (statu) { console.log(statu_in, data_in); } }, }; return diplay; }; $scope.button = ""; $scope.GETstylebutton = function(button) { if (button == undefined || button == "") { $scope.button = "filled_button"; } else { $scope.button = button; } console.log('databutton : ', $scope.button); }; $scope.GETstylebutton($scope.stylebutton); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentVideosListCardMain', function($rootScope, $routeParams) { var templateName = 'componentVideosListCardMain'; var componentMain = 'componentVideosList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', dataout: '=datain', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('componentVideosListTypeA', function($rootScope, $routeParams) { var templateName = 'componentVideosListTypeA'; var componentMain = 'componentVideosList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { limit: '@limit', sort: '@sort', col: '@col', componentcard: '@componentcard', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(col) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[col] != 'undefined' && $scope._col[col] != '') ? $scope._col[col] : 12 : 12; }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._limit = (typeof $scope.limit !== 'undefined' && typeof $scope.limit !== '') ? parseInt($scope.limit) : 6; $scope._sort = (typeof $scope.sort !== 'undefined' && typeof $scope.sort !== '') ? $scope.sort : "video_sort_index_0-9"; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.diplay = function() { var diplay = { consoleLog: function(statu_in, data_in) { var statu = true; if (statu) { console.log(statu_in, data_in); } }, }; return diplay; }; $scope.api = function() { var gaeapi = { checkOk: function(data, callback) { var check_ok = false; var check_data = []; if (data.ok == 1) { check_ok = true; check_data = data; } callback(check_data, check_ok); }, videoListsCheck: function(cur_in, per_in, sortby_in, option_in, callback) { var gaeOutput = []; var option = option_in; var dataSend = { 'cur_page': cur_in, 'per_page': per_in, 'txt_sortby': sortby_in, 'txt_filter_json': JSON.stringify(option), }; $scope.diplay().consoleLog("api : videoListsCheck : dataSend : ", dataSend); GAEAPI.get('video/lists', dataSend).then(function(output) { $scope.diplay().consoleLog("api : videoListsCheck : output : ", output); $scope.api().checkOk(output, function(check_data, check_ok) { $scope.diplay().consoleLog("api : videoListsCheck : checkOk : output : ", output); $scope.diplay().consoleLog("api : videoListsCheck : checkOk : check_data : ", check_data); if (check_ok) { gaeOutput = check_data.data.dataList; } callback(gaeOutput); }); }); }, }; return gaeapi; }; $scope.getApiVideolists = function() { var option_in = { 'badge_id_array': [18] }; $scope._dataArrayState = $scope.StateData(true, false); $scope.api().videoListsCheck(1, $scope._limit, $scope._sort, option_in, function(gaeOutput) { $scope.diplay().consoleLog("getApiVideolists : gaeOutput : ", gaeOutput); $scope._dataArray = gaeOutput; $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.getApiVideolists(); }; return promise; });_ui_share_app.directive('componentVideosListTypeB', function($rootScope, $routeParams) { var templateName = 'componentVideosListTypeB'; var componentMain = 'componentVideosList'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { marginone: '@marginone', margintwo: '@margintwo', col: '@col', mobilesize: '@mobilesize', desktopsize: '@desktopsize', componentcard: '@componentcard', stylebutton: '@stylebutton', componentwait: '@componentwait', limit: '@limit', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = {}; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); /*var txt_filter_json = { 'search': "video" };*/ if ($scope.limit != undefined) { var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_sortby': 'video_sort_index_0-9', /*'txt_filter_json': JSON.stringify(txt_filter_json)*/ }; } else { var dataSend = { 'cur_page': 1, 'per_page': 50, 'txt_sortby': 'video_sort_index_0-9', /*'txt_filter_json': JSON.stringify(txt_filter_json)*/ }; } GAEAPI.get('video/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.enableVideo = function(object) { $('#video-player').html(''); if (object.video_embed_code !== '') { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(object.video_embed_code); $('.outer-video-player[data-id="' + $scope._key() + '"]').addClass('active'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').addClass('after') }, 350); return; } else if (object.video_link !== '') { return window.location.href = object.video_link; } }; $scope.disableVideo = function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').html(''); $('.outer-video-player[data-id="' + $scope._key() + '"]').find('#video-player').removeClass('after'); $timeout(function() { $('.outer-video-player[data-id="' + $scope._key() + '"]').removeClass('active'); $('#video-player').html(''); }, 350); return; }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.viewDataSize = function() { return ($(window).width() > 767) ? $scope.desktopsize : $scope.mobilesize; }; $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; }; return promise; });/* Cart displat at right side of page */ var $virtualCart = {}; /* params */ $virtualCart.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentVirtualCart/"; $virtualCart.templateItem = 'item.php'; $virtualCart.templateRoot = 'root.php'; $virtualCart.assetsPath = CUR_THEME.extensions_url() + '../../assets/'; $virtualCart.indexCout = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseInt(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* Install */ $virtualCart.install = function(shopId, customBuild) { /* dont install in (checkout, login) */ if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/login') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) { this.templateRoot = 'root.php'; this.templateItem = 'item.php'; if (!$('#root-virtual-cart').length) { $.get($virtualCart.path + 'componentVirtualCart.css', function(response) { $('head').append(''); }); $.get($virtualCart.path + 'root.php', { imgpath: this.assetsPath, shopId: shopId, custom: customBuild, path: $virtualCart.path }, function(response) { $('body').append(response); if (shopId != undefined && shopId > 0) { if (shopId == 500) { $('#root-virtual-cart').addClass('on-top'); } } }); /* fix ios height */ var winHightTimer = setTimeout(function() { clearTimeout(winHightTimer); $virtualCart.adjustHeight(); }, 2000); var data = window.location.href; var start = data.indexOf('viewcart'); var end = start + 8; var viewcart = data.substring(start, end); if (viewcart == 'viewcart') { setTimeout(function() { console.log("install : ", viewcart); $("#root-virtual-cart").css("display", "none"); if (shopId == 718) { $('.component-bar').css("display", "none"); } }, 100); } } } }; $virtualCart.api = GURL.base_api_url(); $virtualCart.promotion_id = 0; $virtualCart.is_note_exist = false; /* Fetch UiCart */ var virtualCartFetchTimer; $virtualCart.fetch = function() { var dataSend = {}; var t = this; var getCurrentCart = function(callback) { var dataSend = {}; var timeGetCurrentCart = 0; if (typeof store !== 'undefined' && store.get('gae_cart_id') != undefined) { dataSend.txt_cart_id = parseInt(store.get('gae_cart_id')); } GAEAPI.get('cart/current', dataSend).then(function(e) { timeGetCurrentCart = setTimeout(function() { window.clearTimeout(timeGetCurrentCart); var currentCart = e.data; callback(currentCart); }, 100); }); }; /*var req = $.get($virtualCart.api+'cart/current', dataSendFetch); req.done = function(e){ console.log("$virtualCart: cart/current: ok", e); }; req.error = function(e){ console.log("$virtualCart: cart/current: error", e); }; var r = $.get($virtualCart.api+'cart/current',dataSendFetch).then(function(e){ console.log("$virtualCart: cart/current", e); });*/ getCurrentCart(function(currentCart) { console.log("$virtualCart: fetch: UiCart", currentCart); if (typeof currentCart !== 'undefined' && currentCart != null && currentCart.cart_row_array.length) { if (typeof store !== 'undefined') { store.set('gae_cart_id', currentCart.cart_id); } $('#root-virtual-cart .view-item').html(''); /*document.querySelector('#root-virtual-cart .view-item').innerHTML = '';*/ var currentShopId = parseInt(CUR_THEME.shop_id()); for (var i = 0; i < currentCart.cart_row_array.length; i++) { var item = currentCart.cart_row_array[i]; /* check if note exist */ if (item.note != null && item.note != "") { $virtualCart.is_note_exist = true;; } console.log('cart_row_array', item); var productNode = item.cart_row_display; var product_id = item.object_id || item.product_id; var product_qtn = productNode.amount; var product_compare_price = 0; var product_price = parseInt(productNode.unit_exit_price); var product_title = productNode.title; var product_image = (productNode.image_array.length) ? productNode.image_array[0].image_url : ''; if (currentShopId == 647) { if (product_image == "") { product_image = 'https://image.getappeasy.com/src/images/2000/1036/0206/36206t1503496529.png'; } } var isOption = (productNode.variant_name != '') ? true : false; var dataSend = { shopId: currentShopId, product_id: product_id, product_qtn: product_qtn, product_compare_price: product_compare_price, product_price: product_price, product_title: product_title, product_image: product_image, imgpath: $virtualCart.assetsPath, idx: item.cart_row_id, option_name: (isOption) ? productNode.variant_name : '', note: item.note, discount: $virtualCart.checkDiscountArray(product_id, currentCart.cart_product_discount_array) }; $.post($virtualCart.path + t.templateItem, dataSend, function(e) { $('#root-virtual-cart .view-item').append(e); if ($('#root-virtual-cart .view-item').length > 0) { $('#root-virtual-cart .view-item-none').hide(); } }); } if (currentCart.cart_row_array.length > 0) { $virtualCart.updateSubTotal(currentCart.cart_total_exit_price); /* fetch promotions */ var promotimer = setTimeout(function() { clearTimeout(promotimer); $virtualCart.getPromotion(parseInt(CUR_THEME.shop_id())); }, 1000); } $virtualCart.adjustHeight(); } else { $('.view-promotion-detail').hide(); $('#root-virtual-cart .view-item').html(''); $('#root-virtual-cart .view-item-none').show(); $('#root-virtual-cart .view-item-none').show(); $virtualCart.updateSubTotal(0); $virtualCart.adjustHeight(); } /*var currentCart = UiCart.delegate.get.cartData();*/ virtualCartFetchTimer = setTimeout(function() { /*$('#root-virtual-cart .view-loading').removeClass('is-active');*/ document.querySelector('#root-virtual-cart .view-loading').classList.remove('is-active'); clearTimeout(virtualCartFetchTimer); }, 1000); }); }; $virtualCart.checkDiscountArray = function(product_id, cart_product_discount_array) { var objArray = { 'discount_from': 0, 'discount_to': 0, 'discount_qty': 0 }; if (cart_product_discount_array.length <= 0) { return objArray; } for (var i = 0; i < cart_product_discount_array.length; i++) { if (cart_product_discount_array[i].product_id == product_id) { objArray.discount_from = cart_product_discount_array[i].cart_product_discount_price[0].start_price; objArray.discount_to = parseFloat(cart_product_discount_array[i].cart_product_discount_price[0].start_price - cart_product_discount_array[i].cart_product_discount_price[0].discount_price); objArray.discount_qty = cart_product_discount_array[i].cart_product_discount_price[0].discount_price; break; } } return objArray; }; $virtualCart.getPromotion = function(shopId) { var getPromotionId = function(id, callback) { var d = { 'txt_promotion_id': id }; GAEAPI.get('promotion/id', d).then(function(e) { if (typeof callback != undefined) { callback(e); } }); }; var showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == "18" || objArray[i].badge_id == 18) { r = true; break; } } }; var checkPromo = function(buy, sub) { if (buy.length && sub.length) { return true; } return false; } if (shopId == 647) { /* zaapclassic */ var dataSend = { 'cur_page': 1, 'per_page': 1, 'txt_filter_json': JSON.stringify({ "type_number": 6 }) }; GAEAPI.get('promotion/lists', dataSend).then(function(responseList) { /* console.log("$virtualCart.getPromotion", responseList); */ if (responseList.ok == 1 && responseList.data.dataList.length > 0) { getPromotionId(responseList.data.dataList[0].promotion_id, function(e) { if (e.ok != 1) { return; } return $virtualCart.applyPromotion(e.data); }); } }); } else { var filter_json = { "type_number": 6 } var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_badge_id': 18, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; console.log("getPromotionLists dataSend : ", dataSend); GAEAPI.get('promotion/lists', dataSend).then(function(output) { console.log("getPromotion promotion/lists : ", output.data.dataList); if (output.ok == 1 && output.data.dataList.length > 0) { return $virtualCart.applyPromotionArray(output.data.dataList); } }); } }; $virtualCart.applyPromotionArray = function(objData) { var compare = function(a, b) { if (a.promotion_row_display.buy.order[0].price < b.promotion_row_display.buy.order[0].price) return -1; if (a.promotion_row_display.buy.order[0].price > b.promotion_row_display.buy.order[0].price) return 1; return 0; }; var getDataCart = function() { var currentCart = UiCart.delegate.get.cartData(); return currentCart; } var getPromotionId = function(supPrice, data) { var datareturn = []; for (var i = 0; i < data.length; i++) { var price = data[i].promotion_row_display.buy.order[0].price; if (supPrice >= price) { datareturn = data[i]; break; } } return datareturn; } var getDataOfArray = function(supPrice, data) { var datareturn = []; for (var i = 0; i < data.length; i++) { console.log("getDataOfArray : ", supPrice, data[i].promotion_row_display.buy.order[0].price); if (supPrice < data[i].promotion_row_display.buy.order[0].price) { datareturn = data[i]; break; } else { datareturn = data[i]; } } return datareturn; } var buildTitleRecByCondition = function(currentCart, promotion_row_display) { var txt = ""; var dif = 0; var buyPrice = promotion_row_display.buy.order[0].price; var discountPrice = promotion_row_display.sub.order[0].price; var discountUnit = "THB"; if (promotion_row_display.sub.order[0].percent != "0") { discountPrice = promotion_row_display.sub.order[0].percent; discountUnit = "%"; } var cartPrice = parseFloat(currentCart.cart_total_product_price); if (cartPrice < buyPrice) { txt += "ซื้ออีก " + (buyPrice - cartPrice) + " บาท จะ ได้ส่วนลดรวมเป็น " + discountPrice + discountUnit; } else { txt += "ได้่รับส่วนลด " + discountPrice + discountUnit; } var dataSend = { txt: txt, start: cartPrice, end: buyPrice }; return dataSend; } var getDataSend = function(ibjArray, dataShow) { var dataSend = { title: ibjArray.promotion_title, title_rec: dataShow.txt, start: dataShow.start, end: dataShow.end, percent: parseInt(dataShow.start) * 100 / parseInt(dataShow.end) }; return dataSend; } var applyRenderPromotion = function(dataSend, clear) { console.log("$virtualCart.applyRenderPromotion", dataSend); if (clear != undefined && clear) { $('.view-promotion-detail').hide(); $('.view-promotion-detail .txt_recommend').html(''); $('.view-promotion-detail .txt_price .start').html(''); $('.view-promotion-detail .txt_price .end').html(''); $('.view-promotion-detail .gauge_container .left').css('width', '0%'); return; } /*$('.view-promotion-detail .txt_title').html(dataSend.title);*/ $('.virtual-view-container .view-item-container .view-item').css('max-height', 'calc(100vh - 320px)'); $('.view-promotion-detail').show(); $('.view-promotion-detail .txt_recommend').html(dataSend.title_rec); $('.view-promotion-detail .txt_price .start').html(dataSend.start); $('.view-promotion-detail .txt_price .end').html(dataSend.end); setTimeout(function() { $('.view-promotion-detail .gauge_container .left').css('width', dataSend.percent + '%'); }, 1000); } var savePromotion = function(promotion_id) { var currentCart = UiCart.delegate.get.cartData(); if (currentCart == undefined || currentCart == null) { return; } var dataSend = { 'txt_promotion_id': parseInt(promotion_id), 'txt_cart_id': parseInt(currentCart.cart_id) }; GAEAPI.post('cart/cart_promotion_save', dataSend).then(function(e) { console.log("virtualCart.savePromotion : dataSend", dataSend); console.log("virtualCart.savePromotion : result", e); if (e.ok == 1) { $virtualCart.promotion_id = promotion_id; GAEAPI.get('cart/current', {}).then(function(c) { console.log("virtualCart.savePromotion : cart/current", c); $virtualCart.updateSubTotal(parseFloat(c.data.cart_total_exit_price)); }); } else { $virtualCart.promotion_id = 0; } }); } var maincontrol = function() { objData.sort(compare); var currentCart = getDataCart(); var promotionId = getPromotionId(currentCart.cart_total_product_price, objData); var ibjArray = getDataOfArray(currentCart.cart_total_product_price, objData); var dataShow = buildTitleRecByCondition(currentCart, ibjArray.promotion_row_display); var dataSend = getDataSend(ibjArray, dataShow); console.log("applyPromotionArray maincontrol dataSend : ", dataSend); applyRenderPromotion(dataSend); console.log("maincontrol : promotionId : ", promotionId); $virtualCart.savePromotion(promotionId.promotion_id); }; maincontrol(); }; $virtualCart.applyPromotion = function(objData) { console.log("$virtualCart.applyPromotion", objData); var buildTitleRecByCondition = function(promotion_row_display) { var currentCart = UiCart.delegate.get.cartData(); var txt = ""; var dif = 0; var buyPrice = promotion_row_display.buy.order[0].price; var discountPrice = promotion_row_display.sub.order[0].price; var discountUnit = "THB"; if (promotion_row_display.sub.order[0].percent != "0") { discountPrice = promotion_row_display.sub.order[0].percent; discountUnit = "%"; } var cartPrice = parseFloat(currentCart.cart_subtotal_price); if (cartPrice < buyPrice) { txt += "ซื้ออีก " + (buyPrice - cartPrice) + "THB ได้่รับส่วนลด " + discountPrice + discountUnit; } else { txt += "คุณซื้อสินค้าครบ " + (buyPrice) + " ได้่รับส่วนลด " + discountPrice + discountUnit; } var dataSend = { txt: txt, start: cartPrice, end: buyPrice }; return dataSend; }; if (objData.promotion_row_display.buy.order.length && objData.promotion_row_display.sub.order.length) { var buildTitleParams = buildTitleRecByCondition(objData.promotion_row_display); var dataSend = { title: objData.promotion_title, title_rec: buildTitleParams.txt, start: buildTitleParams.start, end: buildTitleParams.end, percent: parseInt(buildTitleParams.start) * 100 / parseInt(buildTitleParams.end) }; $virtualCart.applyRenderPromotion(dataSend); $virtualCart.savePromotion(objData.promotion_id); } }; $virtualCart.applyRenderPromotion = function(dataSend, clear) { console.log("$virtualCart.applyRenderPromotion", dataSend); if (clear != undefined && clear) { $('.view-promotion-detail').hide(); $('.view-promotion-detail .txt_recommend').html(''); $('.view-promotion-detail .txt_price .start').html(''); $('.view-promotion-detail .txt_price .end').html(''); $('.view-promotion-detail .gauge_container .left').css('width', '0%'); return; } /*$('.view-promotion-detail .txt_title').html(dataSend.title);*/ $('.view-promotion-detail').show(); $('.view-promotion-detail .txt_recommend').html(dataSend.title_rec); $('.view-promotion-detail .txt_price .start').html(dataSend.start + 'THB'); $('.view-promotion-detail .txt_price .end').html(dataSend.end + 'THB'); setTimeout(function() { $('.view-promotion-detail .gauge_container .left').css('width', dataSend.percent + '%'); }, 1000); }; $virtualCart.adjustHeight = function() { if (window.innerWidth <= 767) { var headBar = 60; var headText = $(".view-item-none").height() + 15; if (document.querySelector(".view-item-none").style.display == "none") { headText = 0; } var bottomBar = 75; var heightToDelete = headBar + headText + bottomBar + 60; /*var heightAdjust = 'calc(' + window.innerHeight + 'px - ' + (heightToDelete) + 'px)';*/ /* $('.virtual-view-container .view-item-container .view-item').addClass('adjust-height').css({'height':heightAdjust}); */ document.querySelector('.virtual-view-container .view-item-container .view-item').classList.add('adjust-height'); /*document.querySelector('.virtual-view-container .view-item-container .view-item').style.height = heightAdjust;*/ } }; /* Open */ var timerAdjustOpen = 0; $virtualCart.isOpen = false; $virtualCart.open = function() { if (!$virtualCart.isOpen) { console.log("virtualCart : case : opening"); /*$('.virtual-view-container').addClass('is-open');*/ document.querySelector('.virtual-view-container').classList.add('is-open'); if ($(window).width() <= 991) { $('body').css({ 'position': 'fixed', 'overflow': 'hidden' }); } timerAdjustOpen = setTimeout(function() { clearTimeout(timerAdjustOpen); $virtualCart.adjustHeight(); $virtualCart.active(); }, 300); $virtualCart.isOpen = true; } else { console.log("virtualCart : case : closing..."); /*$('.virtual-view-container').removeClass('is-open');*/ document.querySelector('.virtual-view-container').classList.remove('is-open'); if ($(window).width() <= 991) { $('body').css({ 'position': 'relative', 'overflow': 'auto' }); } $virtualCart.isOpen = false; $virtualCart.applyRenderPromotion({}, true); } }; /* Close */ $virtualCart.active = function() { /* Add Loading */ /*if(!$('#root-virtual-cart .view-loading').hasClass('is-active')){ $('#root-virtual-cart .view-loading').addClass('is-active'); }*/ if (!document.querySelector('#root-virtual-cart .view-loading').classList.contains('is-active')) { document.querySelector('#root-virtual-cart .view-loading').classList.add('is-active'); } /* Fetch Api */ $virtualCart.fetch(); } $virtualCart.updateSubTotal = function(privatePrice) { console.log("updateSubTotal", privatePrice); if (typeof privatePrice !== 'undefined' && privatePrice > 0) { $('#root-virtual-cart .view-cart').find('.t2').text(privatePrice); /*document.querySelector('#root-virtual-cart .view-cart .t2').innerHTML = pp.formatMoney(0, '', ',');*/ return; } var p = 0; $('#root-virtual-cart .p').each(function(idx, obj) { var thisPrice = parseInt($(this).find('.product_price').attr('data-price')); p = p + thisPrice; }); /*$('#root-virtual-cart .view-cart').find('.t2').text(p.formatMoney(0, '', ','));*/ document.querySelector('#root-virtual-cart .view-cart .t2').innerHTML = p.formatMoney(0, '', ','); if (p <= 0) { /*$('#root-virtual-cart .view-item-none').show();*/ document.querySelector('#root-virtual-cart .view-item-none').style.display = 'block'; } }; $virtualCart.productUpdate = function(productId, qty, callback) {}; /* Add */ $virtualCart.add = function(el, privateDataObj) { if (!$('.virtual-view-container').hasClass('is-open')) { $('.virtual-view-container').toggleClass('is-open'); } if ($('.virtual-view-container').hasClass('is-open')) { if (!$('#root-virtual-cart .view-loading').hasClass('is-active')) { $('#root-virtual-cart .view-loading').addClass('is-active'); } } var product_id = el.getAttribute('data-product'); var product_qtn = 1; var t = this; UiCart.delegate.product.add(product_id, product_qtn, function(e) { $virtualCart.addSuccess(product_id); console.log("$virtualCart add callback", e); }); /*console.log("$virtualCart: add", product_id, product_qtn);*/ /*var t = setInterval(function(){ if(!UiCart.delegate.product.isProgress(product_id)){ window.clearInterval(t); $virtualCart.active(product_id); } },500);*/ /*if(typeof privateDataObj !== 'undefined'){ var product_id = el.getAttribute('data-product'); var product_compare_price = el.getAttribute('data-compare'); var product_price = el.getAttribute('data-price'); var product_title = el.getAttribute('data-title'); var product_image = el.getAttribute('data-image'); } else { var product_id = el.getAttribute('data-product'); var product_compare_price = el.getAttribute('data-compare'); var product_price = el.getAttribute('data-price'); var product_title = el.getAttribute('data-title'); var product_image = el.getAttribute('data-image'); }*/ /* Check If Option */ /*var isOption = (el.getAttribute('data-option') == 1) ? true : false; var findOptionName = function(){ return $('.o_item_list .list_option.active').text(); }; if(product_price <= 0){ return; } var dataSend = { product_id: product_id, product_qtn: 1, product_compare_price: product_compare_price || 0, product_price: product_price || 0, product_title: product_title || '', product_image: product_image || '', imgpath: this.assetsPath, idx: $virtualCart.indexCout, option_name: (isOption) ? findOptionName() : '' }; $.post($virtualCart.path+t.templateItem,dataSend, function(e){ $virtualCart.indexCout = $virtualCart.indexCout + 1; $('#root-virtual-cart .view-item').append(e); if($('#root-virtual-cart .view-item').length > 0){ $('#root-virtual-cart .view-item-none').hide(); } if(!$('.virtual-view-container').hasClass('is-open')){ $('.virtual-view-container').addClass('is-open'); } $virtualCart.updateSubTotal(); }); */ }; $virtualCart.addSuccess = function() {}; $virtualCart.virItemQUp = function(productId, idx) { var element = $('#root-virtual-cart .p[data-index="' + idx + '"][data-id="' + productId + '"]'); var _old_qtn = parseInt(element.find('.qty').text()); var _new_qtn = _old_qtn + 1; /*console.log("$virtualCart: up", _new_qtn);*/ /* Add Loading */ /*if(!$('#root-virtual-cart .view-loading').hasClass('is-active')){ $('#root-virtual-cart .view-loading').addClass('is-active'); }*/ if (!document.querySelector('#root-virtual-cart .view-loading').classList.contains('is-active')) { document.querySelector('#root-virtual-cart .view-loading').classList.add('is-active'); } UiCart.delegate.product.updateAmount(productId, _new_qtn); setTimeout(function() { var t = setInterval(function() { if (!UiCart.delegate.product.isProgress(productId)) { window.clearInterval(t); $virtualCart.active(); } }, 300); }, 300); }; $virtualCart.virItemQdown = function(productId, idx) { var element = $('#root-virtual-cart .p[data-index="' + idx + '"][data-id="' + productId + '"]'); var _old_qtn = parseInt(element.find('.qty').text()); var _new_qtn = _old_qtn - 1; console.log("$virtualCart: down", _new_qtn); if (_new_qtn >= 1) { /* re-assign */ /*element.find('.qty').text(_old_qtn - 1); element.find('.product_price').text(_new_price); element.find('.product_price').attr('data-price',_old_price * (_old_qtn - 1)); UiCart.delegate.product.updateAmount(productId,_old_price * (_old_qtn - 1));*/ /* Add Loading */ /*if(!$('#root-virtual-cart .view-loading').hasClass('is-active')){ $('#root-virtual-cart .view-loading').addClass('is-active'); }*/ if (!document.querySelector('#root-virtual-cart .view-loading').classList.contains('is-active')) { document.querySelector('#root-virtual-cart .view-loading').classList.add('is-active'); } UiCart.delegate.product.updateAmount(productId, _new_qtn); setTimeout(function() { var t = setInterval(function() { if (!UiCart.delegate.product.isProgress(productId)) { window.clearInterval(t); $virtualCart.active(); } }, 500); }, 500); } }; $virtualCart.virItemKill = function(productId, idx) { /* Add Loading */ /*if(!$('#root-virtual-cart .view-loading').hasClass('is-active')){ $('#root-virtual-cart .view-loading').addClass('is-active'); }*/ if (!document.querySelector('#root-virtual-cart .view-loading').classList.contains('is-active')) { document.querySelector('#root-virtual-cart .view-loading').classList.add('is-active'); } UiCart.delegate.product.updateAmount(productId, 0); var t = setInterval(function() { if (!UiCart.delegate.product.isSelected(productId)) { window.clearInterval(t); $virtualCart.fetch(); } }, 500); }; $virtualCart.prepareToCheckout = function() { var strRetrun = 'checkout?pdata='; var strArray = []; var strPromo = ''; var strCartId = ''; $.each($('.virtual-view-container .view-item .p'), function(k, item) { var note = ($(this).attr('data-note') != "") ? $(this).attr('data-note').replace(/-/g, '+') : ""; strArray.push($(this).attr('data-id') + '-' + parseInt($(this).find('.qty').text()) + '-' + note); }); if ($virtualCart.promotion_id != 0 && $virtualCart.promotion_id > 0) { strPromo = '&promotion_id=' + $virtualCart.promotion_id; } if ($virtualCart.is_note_exist && typeof store.get('gae_cart_id') !== 'undefined' && store.get('gae_cart_id') != "") { strCartId = '&txt_cart_id=' + store.get('gae_cart_id'); } return strRetrun + strArray.join(',') + strPromo + strCartId; }; $virtualCart.virOpenCart = function() { /* if nothing in cart */ var totalItems = $('.virtual-view-container .view-item .p').length; if (totalItems <= 0) { return false; } /* close panel and open uicart interface */ /*if($('.virtual-view-container').hasClass('is-open')){ $('.virtual-view-container').removeClass('is-open'); } setTimeout(function(){ UiCart.delegate.modal.open(); }, 400);*/ /* redirect to checkout page */ var strUrl = GURL.base_url() + this.prepareToCheckout(); console.log("strUrl : ", strUrl); return window.location.href = strUrl; }; $virtualCart.strToUrl = function(strUrl) { var url = GURL.base_url() + strUrl; console.log("strToUrl : url : ", url); return window.location.href = url; }; $virtualCart.savePromotion = function(promotion_id) { var currentCart = UiCart.delegate.get.cartData(); if (currentCart == undefined || currentCart == null) { return; } var dataSend = { 'txt_promotion_id': parseInt(promotion_id), 'txt_cart_id': parseInt(currentCart.cart_id) }; console.log("savePromotion dataSend : ", dataSend); GAEAPI.post('cart/cart_promotion_save', dataSend).then(function(e) { console.log("virtualCart.savePromotion : dataSend", dataSend); console.log("virtualCart.savePromotion : result", e); if (e.ok == 1) { $virtualCart.promotion_id = promotion_id; GAEAPI.get('cart/current', { 'txt_cart_id': e.data[0].cart_id }).then(function(c) { console.log("virtualCart.savePromotion : cart/current", c); $virtualCart.updateSubTotal(parseFloat(c.data.cart_total_exit_price)); }); /*$virtualCart.updateSubTotal(parseFloat(e.data.cart_total_exit_price));*/ } else { $virtualCart.promotion_id = 0; } }); }; /* declare global window params */ window.$virtualCart = $virtualCart; /* Init */ /* Init */ /* Init */ $(function() { var currentShopId = parseInt(CUR_THEME.shop_id()); switch (currentShopId) { /* normal design */ case 395: /*gaedemo101*/ case 414: /* sava */ case 481: /* wego */ case 483: /* apbeauty */ // case 498: /* xx */ /* case 699: */ /* xx */ /* case 676: */ /* case 635: */ case 646: /* case 717: */ /* case 718: */ /* case 723: */ /* case 726: */ case 401: /* case 728: */ /* case 731: */ /* case 740: */ case 439: /* case 737: */ /* case 742: */ /* case 732: */ /* case 743: */ /* case 636: */ /* case 738: */ case 722: case 476: /* case 459: */ /* case 747: */ /* case 753: */ /* case 754: */ case 647: /* zaapclassic */ $virtualCart.install(currentShopId, true); default: break; } });/* Cart displat at right side of page */ var $virtualCartTypeA = {}; /* params */ $virtualCartTypeA.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentVirtualCartTypeA/"; $virtualCartTypeA.icnPath = CUR_THEME.extensions_url() + '../../assets/'; $virtualCartTypeA.templateItem = 'item.php'; $virtualCartTypeA.templateRoot = 'root.php'; $virtualCartTypeA.api = GURL.base_api_url(); $virtualCartTypeA.indexCout = 0; $virtualCartTypeA.shopId = 0; $virtualCartTypeA.PromotionId = 0; Number.prototype.formatMoney = function(c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = String(parseFloat(n = Math.abs(Number(n) || 0).toFixed(c))), j = (j = i.length) > 3 ? j % 3 : 0; return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); }; /* set language */ $virtualCartTypeA.setLanguage = function(language) { var language_data = { en: { order: 'Order Summary ', checkout: 'CHECKOUT', continued: 'BUY MORE', shopping: 'Shopping Cart', empty: 'Your cart is empty', }, th: { order: 'สรุปรายการสั่งซื้อ', checkout: 'ไปขั้นตอนการสั่งซื้อและชำระเงิน ', continued: 'เลือกซื้อสินค้าอื่น', shopping: 'รายการสั่งซื้อ', empty: 'ยังไม่มีสินค้าในรถเข็น', } }; var data = {}; switch (language) { case 'en': return data = language_data.en; break; case 'th': return data = language_data.th; break; default: return data = language_data.en; break; } }; /* Install */ $virtualCartTypeA.install = function(language, shopId, iconOpen, iconClose, iconNone, textNone) { if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/login') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) { var languageData = $virtualCartTypeA.setLanguage(language); $virtualCartTypeA.shopId = shopId; /* dont install in (viewcart) */ var rootVirtualCart = $('#root-virtual-cart-type-a'); this.templateRoot = 'root.php'; this.templateItem = 'item.php'; if (!rootVirtualCart.length) { $.get($virtualCartTypeA.path + 'componentVirtualCartTypeA.css', function(response) { $('head').append(''); }); $.get($virtualCartTypeA.path + 'root.php', { order: languageData.order, checkout: languageData.checkout, continued: languageData.continued, imgpath: this.icnPath, iconOpen: iconOpen, iconClose: iconClose, iconNone: iconNone, textNone: textNone, shopId: shopId, path: $virtualCartTypeA.path }, function(response) { $('body').append(response); }); } } else {} }; /* Install */ $virtualCartTypeA.displayView = function() { var functionIN = { cartContainer: function() { var container = $('.virtual-view-container-type-a'); return container; }, cartContainerLoader: function() { var loader = $('.virtual-view-container-type-a .view-item-loader-type-a'); return loader; }, cartContainerToPromotion: function() { var promotion = $('.virtual-view-container-type-a .view-to-promotion'); return promotion; }, cartContainerApplyPromotion: function() { var promotion = $('.virtual-view-container-type-a .view-to-promotion .cover-apply-promotion'); return promotion; }, cartContainerPromotion: function() { var promotion = $('.virtual-view-container-type-a .view-to-promotion .cover-promotion'); return promotion; }, itemNone: function() { var item = $('.virtual-view-container-type-a .view-item-none-type-a'); return item; }, inProduct: function() { var product = $('#root-virtual-cart-type-a .view-item-container-type-a .view-item-type-a'); return product; }, buttonBuyProduct: function() { var button = $('.virtual-view-container-type-a .cover-button'); return button; }, open: function() { var body = $('body'); var cart = $virtualCartTypeA.displayView().cartContainer(); if ($(window).width() <= 676) { body.css({ 'position': 'relative', 'overflow': 'hidden' }); } cart.addClass('is-open'); }, close: function() { var body = $('body'); var cart = $virtualCartTypeA.displayView().cartContainer(); body.css({ 'position': 'relative', 'overflow': 'auto' }); cart.removeClass('is-open'); }, getStatusLoader: function() { var cart = $virtualCartTypeA.displayView().cartContainerLoader(); return cart.hasClass("is-open"); }, openPromotionLoader: function() { var cart = $virtualCartTypeA.displayView().cartContainerToPromotion(); if (cart.hasClass("is-open")) { cart.removeClass('is-open'); } }, closePromotionLoader: function() { var cart = $virtualCartTypeA.displayView().cartContainerToPromotion(); if (!cart.hasClass("is-open")) { cart.addClass('is-open'); } }, openLoader: function() { var cart = $virtualCartTypeA.displayView().cartContainerLoader(); if (!cart.hasClass("is-open")) { cart.addClass('is-open'); } }, closeLoader: function() { var cart = $virtualCartTypeA.displayView().cartContainerLoader(); if (cart.hasClass("is-open")) { cart.removeClass('is-open'); } }, closeItemNone: function() { var not = $virtualCartTypeA.displayView().itemNone(); if (!not.hasClass("is-not")) { not.addClass('is-not'); } }, openItemNone: function() { var not = $virtualCartTypeA.displayView().itemNone(); if (not.hasClass("is-not")) { not.removeClass('is-not'); } }, openButtonBuy: function() { var button = $virtualCartTypeA.displayView().buttonBuyProduct(); if (!button.hasClass("is-open")) { button.addClass('is-open'); } }, closeButtonBuy: function() { var button = $virtualCartTypeA.displayView().buttonBuyProduct(); if (button.hasClass("is-open")) { button.removeClass('is-open'); } $virtualCartTypeA.displayView().resetPromotion(); }, openPromotion: function() { var apply = $virtualCartTypeA.displayView().cartContainerApplyPromotion(); var promotion = $virtualCartTypeA.displayView().cartContainerPromotion(); if (!promotion.hasClass("is-open") && !apply.hasClass("is-open")) { promotion.addClass('is-open'); } }, closePromotion: function() { var promotion = $virtualCartTypeA.displayView().cartContainerPromotion(); if (promotion.hasClass("is-open")) { promotion.removeClass('is-open'); } $virtualCartTypeA.displayView().resetPromotion(); }, openApplyPromotion: function() { var apply = $virtualCartTypeA.displayView().cartContainerApplyPromotion(); var promotion = $virtualCartTypeA.displayView().cartContainerPromotion(); if (!apply.hasClass("is-open") && !promotion.hasClass("is-open")) { apply.addClass('is-open'); } }, closeApplyPromotion: function() { var promotion = $virtualCartTypeA.displayView().cartContainerApplyPromotion(); if (promotion.hasClass("is-open")) { promotion.removeClass('is-open'); } }, cartContainerPromotionPrice: function() { var price = $('#root-virtual-cart-type-a .view-item-container-type-a .view-to-promotion .cover-gauge'); return price; }, priceReplace: function(price) { return price.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); }, resetPromotion: function() { $virtualCartTypeA.displayView().showPromotionTitle(''); $virtualCartTypeA.displayView().showPromotionGauge(0, 0); $virtualCartTypeA.displayView().cartContainerPromotionPrice().find('.start').text(0); $virtualCartTypeA.displayView().cartContainerPromotionPrice().find('.end').text(0); }, showApplyPromotionTitle: function(title) { $('#root-virtual-cart-type-a .view-item-container-type-a .view-to-promotion').find('.txt_apply_title').text(title); }, showPromotionTitle: function(title) { $('#root-virtual-cart-type-a .view-item-container-type-a .view-to-promotion').find('.txt_title').text(title); }, showPromotionGauge: function(percent, time) { setTimeout(function() { $('#root-virtual-cart-type-a .view-item-container-type-a .view-to-promotion .gauge_container .gauge').css('width', percent + '%'); }, time); }, showPromotionStartCoverGauge: function(status) { var coverGauge = $virtualCartTypeA.displayView().cartContainerPromotionPrice(); if (status == 'show') { coverGauge.show(); } else if (status == 'hide') { coverGauge.hide(); } else { coverGauge.show(); } }, showPromotionStart: function(price) { var replace = $virtualCartTypeA.displayView().priceReplace(price); $virtualCartTypeA.displayView().cartContainerPromotionPrice().find('.start').text(replace); }, showPromotionEnd: function(price) { var replace = $virtualCartTypeA.displayView().priceReplace(price); $virtualCartTypeA.displayView().cartContainerPromotionPrice().find('.end').text(replace); }, resetItem: function() { $('#root-virtual-cart-type-a .view-item-container-type-a .view-item-type-a').html(''); }, itemProduct: function() { var product = $('#root-virtual-cart-type-a .view-item-container-type-a .view-item-type-a'); return product; }, editItem: function() { var item = $virtualCartTypeA.displayView().itemProduct(); if (!item.hasClass("edit")) { item.addClass('edit'); } }, notEditItem: function() { var item = $virtualCartTypeA.displayView().itemProduct(); if (item.hasClass("edit")) { item.removeClass('edit'); } }, statusEditItem: function() { var item = $virtualCartTypeA.displayView().itemProduct(); return item.hasClass("edit"); }, productIdQty: function(product_id, qty) { return $('#root-virtual-cart-type-a .cover-product[data-index="' + qty + '"][data-id="' + product_id + '"]'); }, updatesubtotal: function(price) { $('#root-virtual-cart-type-a .cover-button').find('.button-price').text(price); }, totalItems: function() { return $('.view-item-container-type-a .view-item-type-a .cover-product').length; }, }; return functionIN; }; /* Refresh */ $virtualCartTypeA.is_note_exist = false; $virtualCartTypeA.refreshData = function() { var dataSend = {}; var t = this; var getCurrentCart = function(callback) { var dataSend = {}; var timeGetCurrentCart = 0; if (typeof store !== 'undefined' && store.get('gae_cart_id') != undefined) { dataSend.txt_cart_id = parseFloat(store.get('gae_cart_id')); } GAEAPI.get('cart/current', dataSend).then(function(e) { timeGetCurrentCart = setTimeout(function() { window.clearTimeout(timeGetCurrentCart); var currentCart = e.data; callback(currentCart); }, 100); }); }; getCurrentCart(function(currentCart) { console.log("$virtualCartTypeA: refreshData: UiCart", currentCart); var shopId = parseFloat($virtualCartTypeA.shopId); if (typeof currentCart !== 'undefined' && currentCart != null && currentCart.cart_row_array.length) { if (typeof store !== 'undefined') { store.set('gae_cart_id', currentCart.cart_id); } var rootViewItem = $virtualCartTypeA.displayView().inProduct(); $virtualCartTypeA.displayView().resetItem(); if (!$virtualCartTypeA.displayView().statusEditItem()) { $virtualCartTypeA.displayView().editItem(); for (var i = 0; i < currentCart.cart_row_array.length; i++) { var item = currentCart.cart_row_array[i]; if (item.note != null && item.note != "") { $virtualCartTypeA.is_note_exist = true; } console.log('cart_row_array', item); var productNode = item.cart_row_display; var product_id = item.object_id || item.product_id; var product_qtn = productNode.amount; var product_compare_price = 0; var product_price = parseFloat(productNode.unit_exit_price); var product_title = productNode.title; var product_image = (productNode.image_array.length) ? productNode.image_array[0].image_url : ''; var isOption = (productNode.variant_name != '') ? true : false; var dataSend = { shopId: shopId, product_id: product_id, product_qtn: product_qtn, product_compare_price: product_compare_price, product_price: product_price, product_title: product_title, product_image: product_image, imgpath: $virtualCartTypeA.icnPath, idx: item.cart_row_id, option_name: (isOption) ? productNode.variant_name : '', note: item.note, discount: $virtualCartTypeA.checkDiscountArray(product_id, currentCart.cart_product_discount_array) }; $.post($virtualCartTypeA.path + t.templateItem, dataSend, function(e) { rootViewItem.append(e); }); } } $virtualCartTypeA.displayView().notEditItem(); if (currentCart.cart_row_array.length > 0) { $virtualCartTypeA.displayView().closeItemNone(); $virtualCartTypeA.updateSubTotal(currentCart.cart_total_exit_price); $virtualCartTypeA.displayView().openButtonBuy(); var time = setTimeout(function() { clearTimeout(time); $virtualCartTypeA.getPromotion(); }, 1000); } } else { $virtualCartTypeA.displayView().closePromotionLoader(); $virtualCartTypeA.displayView().openItemNone(); $virtualCartTypeA.displayView().closeButtonBuy(); $virtualCartTypeA.displayView().resetItem(); $virtualCartTypeA.updateSubTotal(0); $virtualCartTypeA.displayView().closePromotion(); } var time = setTimeout(function() { $virtualCartTypeA.displayView().closeLoader(); clearTimeout(time); }, 500); }); } /* Refresh */ /* updateSubTotal */ $virtualCartTypeA.updateSubTotal = function(privatePrice) { console.log("$virtualCartTypeA.updateSubTotal : ", privatePrice); var supTotal = privatePrice.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"); $virtualCartTypeA.displayView().updatesubtotal(supTotal); }; /* updateSubTotal */ /* CheckDiscountArray */ $virtualCartTypeA.checkDiscountArray = function(product_id, cart_product_discount_array) { var objArray = { 'discount_from': 0, 'discount_to': 0, 'discount_qty': 0 }; if (cart_product_discount_array.length <= 0) { return objArray; } for (var i = 0; i < cart_product_discount_array.length; i++) { if (cart_product_discount_array[i].product_id == product_id) { objArray.discount_from = cart_product_discount_array[i].cart_product_discount_price[0].start_price; objArray.discount_to = parseFloat(cart_product_discount_array[i].cart_product_discount_price[0].start_price - cart_product_discount_array[i].cart_product_discount_price[0].discount_price); objArray.discount_qty = cart_product_discount_array[i].cart_product_discount_price[0].discount_price; break; } } return objArray; }; /* CheckDiscountArray */ /* getPromotion */ $virtualCartTypeA.getPromotion = function() { var filter_json = { "type_number": 6 } var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_badge_id': 18, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(filter_json) }; console.log("$virtualCartTypeA.getPromotion : dataSend : ", dataSend); GAEAPI.get('promotion/lists', dataSend).then(function(output) { if (output.ok == 1) { console.log("$virtualCartTypeA.getPromotion : output ", output); var productArray = output.data.dataList; if (!productArray.length == false) { $virtualCartTypeA.displayView().openPromotionLoader(); $virtualCartTypeA.applyPromotion(productArray); } else { $virtualCartTypeA.displayView().closePromotionLoader(); } } }); }; /* getPromotion */ /* applyPromotion */ $virtualCartTypeA.applyPromotion = function(objData) { console.log("$virtualCartTypeA.applyPromotion : ", objData); var comparePriceMaxToMin = function(a, b) { return b.promotion_row_display.buy.order[0].price - a.promotion_row_display.buy.order[0].price; }; var comparePriceMinToMax = function(a, b) { return a.promotion_row_display.buy.order[0].price - b.promotion_row_display.buy.order[0].price; }; var getDataCart = function() { var cartData = UiCart.delegate.get.cartData(); return cartData; } var getDataCartPrice = function() { var cartData = UiCart.delegate.get.cartData(); return cartData.cart_total_product_price; } var applyPromotion = function(objData) { var sumPrice = getDataCartPrice(); objData.sort(comparePriceMaxToMin); var datareturn = []; for (var i = 0; i < objData.length; i++) { var price = objData[i].promotion_row_display.buy.order[0].price; console.log("$virtualCartTypeA.applyPromotion : applyPromotion : ", sumPrice, " >= ", price); if (parseFloat(sumPrice) >= parseFloat(price)) { datareturn = objData[i]; break } } return datareturn; } var applyToPromotion = function(objData) { var sumPrice = getDataCartPrice(); objData.sort(comparePriceMinToMax); var datareturn = []; for (var i = 0; i < objData.length; i++) { var price = objData[i].promotion_row_display.buy.order[0].price; console.log("$virtualCartTypeA.applyPromotion : applyToPromotion : ", sumPrice, " < ", price); if (parseFloat(sumPrice) < parseFloat(price)) { datareturn = objData[i]; break; } else { datareturn = objData[i]; } } return datareturn; } var returnApplyTitlePromotion = function(objData) { console.log("$virtualCartTypeA.applyPromotion : returnApplyTitlePromotion : ", objData); var discount = ""; var discountUnit = ""; var statusPercent = objData.promotion_row_display.sub.order[0].percent; if (statusPercent != "0") { discount = objData.promotion_row_display.sub.order[0].percent; discountUnit = "%"; } else { discount = objData.promotion_row_display.sub.order[0].price; discountUnit = " บาท"; } var txt = ""; txt += "ได้ส่วนลด " + discount + discountUnit; return txt; } var returnTitlePromotion = function(objData) { var sumPrice = parseFloat(getDataCartPrice()); var price = objData.promotion_row_display.buy.order[0].price; var discount = ""; var discountUnit = ""; var statusPercent = objData.promotion_row_display.sub.order[0].percent; if (statusPercent != "0") { discount = objData.promotion_row_display.sub.order[0].percent; discountUnit = "%"; } else { discount = objData.promotion_row_display.sub.order[0].price; discountUnit = " บาท"; } var txt = ""; if (sumPrice < price) { txt += "ซื้ออีก " + (price - sumPrice) + " บาท จะ ได้ส่วนลดรวมเป็น " + discount + discountUnit; } else { txt += "ได้ส่วนลด " + discount + discountUnit; } var dataSend = { txt: txt, start: sumPrice, end: price }; return dataSend; } var returnDataSend = function(objData, data) { var dataSend = { title: objData.promotion_title, title_rec: data.txt, start: data.start, end: data.end, percent: parseFloat(data.start) * 100 / parseFloat(data.end) }; return dataSend; } var displayViewPromotion = function(dataSend) { console.log("$virtualCartTypeA.applyPromotion : savePromotion : displayViewPromotion : ", dataSend); $virtualCartTypeA.displayView().openPromotion(); $virtualCartTypeA.displayView().showPromotionTitle(dataSend.title_rec); $virtualCartTypeA.displayView().showPromotionGauge(dataSend.percent, 500); if (dataSend.start < dataSend.end) { $virtualCartTypeA.displayView().showPromotionStart(dataSend.start); $virtualCartTypeA.displayView().showPromotionEnd(dataSend.end); $virtualCartTypeA.displayView().showPromotionStartCoverGauge('show'); } else { $virtualCartTypeA.displayView().showPromotionStartCoverGauge('hide'); } } var savePromotion = function(promotion_id) { var dataCart = getDataCart(); if (dataCart == undefined || dataCart == null) { return; } var dataSend = { 'txt_promotion_id': parseFloat(promotion_id), 'txt_cart_id': parseFloat(dataCart.cart_id) }; console.log("$virtualCartTypeA.applyPromotion : savePromotion : dataSend : ", dataSend); GAEAPI.post('cart/cart_promotion_save', dataSend).then(function(output) { console.log("$virtualCartTypeA.applyPromotion : savePromotion : output : ", output); var cartid = output.data[0].cart_id; if (output.ok == 1) { var dataSendCurrent = { 'txt_cart_id': cartid }; GAEAPI.get('cart/current', dataSendCurrent).then(function(output_current) { console.log("$virtualCartTypeA.applyPromotion : savePromotion : output : output_current : $virtualCartTypeA.applyPromotion : savePromotion : output : output_current : ", output_current); $virtualCartTypeA.updateSubTotal(parseFloat(output_current.data.cart_total_exit_price)); }); } }); } var displayViewApplyPromotion = function(promotion_id, title, dataSend, time) { console.log("$virtualCartTypeA.applyPromotion : displayViewApplyPromotion : ", title, time); console.log("$virtualCartTypeA.applyPromotion : displayViewApplyPromotion : ", $virtualCartTypeA.PromotionId, " != ", promotion_id); if ($virtualCartTypeA.PromotionId != promotion_id) { $virtualCartTypeA.PromotionId = promotion_id; $virtualCartTypeA.displayView().closePromotion(); $virtualCartTypeA.displayView().showApplyPromotionTitle(title); $virtualCartTypeA.displayView().openApplyPromotion(); setTimeout(function() { $virtualCartTypeA.displayView().closeApplyPromotion(); displayViewPromotion(dataSend); }, time); } else { displayViewPromotion(dataSend); } } var maincontrol = function() { console.log("$virtualCartTypeA.applyPromotion : maincontrol : compare : ", objData); var objDataPromotion = applyPromotion(objData); console.log("$virtualCartTypeA.applyPromotion : maincontrol : applyPromotion : ", objDataPromotion); var applyPromotionTitle = returnApplyTitlePromotion(objDataPromotion); console.log("$virtualCartTypeA.applyPromotion : maincontrol : returnApplyTitlePromotion : ", applyPromotionTitle); var objDataToPromotion = applyToPromotion(objData); console.log("$virtualCartTypeA.applyPromotion : maincontrol : applyToPromotion : ", objDataToPromotion); var promotionTitle = returnTitlePromotion(objDataToPromotion); console.log("$virtualCartTypeA.applyPromotion : maincontrol : returnTitlePromotion : ", promotionTitle); var dataSend = returnDataSend(objDataToPromotion, promotionTitle); console.log("$virtualCartTypeA.applyPromotion : maincontrol : returnDataSend : ", dataSend); var promotion_id = objDataPromotion.promotion_id; console.log("$virtualCartTypeA.applyPromotion : maincontrol : objDataPromotion.promotion_id : ", promotion_id); savePromotion(promotion_id); displayViewApplyPromotion(promotion_id, applyPromotionTitle, dataSend, 3000); }; maincontrol(); }; /* applyPromotion */ /* LoadData */ $virtualCartTypeA.load = function() { $virtualCartTypeA.displayView().openPromotionLoader(); $virtualCartTypeA.displayView().openLoader(); $virtualCartTypeA.refreshData(); } /* LoadData */ /* virItemKill */ $virtualCartTypeA.virItemKill = function(product_id, idx) { console.log("$virtualCartTypeA.virItemKill : ", " ID : ", product_id, " IDX : ", idx); $virtualCartTypeA.displayView().openLoader(); UiCart.delegate.product.updateAmount(product_id, 0); var time = setInterval(function() { console.log("$virtualCartTypeA.virItemKill : ", " !UiCart.delegate.product.isSelected(", product_id, ") :", !UiCart.delegate.product.isSelected(product_id)); /* log */ if (!UiCart.delegate.product.isSelected(product_id)) { window.clearInterval(time); $virtualCartTypeA.refreshData(); } }, 500); } /* virItemKill */ /* virItemQUp */ $virtualCartTypeA.virItemQUp = function(product_id, idx) { var element = $virtualCartTypeA.displayView().productIdQty(product_id, idx); var _old_qtn = parseFloat(element.find('.qty').text()); var _new_qtn = _old_qtn + 1; $virtualCartTypeA.displayView().openLoader(); UiCart.delegate.product.updateAmount(product_id, _new_qtn); var time = setInterval(function() { if (!UiCart.delegate.product.isProgress(product_id)) { window.clearInterval(time); $virtualCartTypeA.load(); } }, 500); } /* virItemQUp */ /* virItemQDown */ $virtualCartTypeA.virItemQDown = function(product_id, idx) { var element = $virtualCartTypeA.displayView().productIdQty(product_id, idx); var _old_qtn = parseFloat(element.find('.qty').text()); var _new_qtn = _old_qtn - 1; $virtualCartTypeA.displayView().openLoader(); UiCart.delegate.product.updateAmount(product_id, _new_qtn); var time = setInterval(function() { if (!UiCart.delegate.product.isProgress(product_id)) { window.clearInterval(time); $virtualCartTypeA.load(); } }, 500); } /* virItemQDown */ /* Open */ $virtualCartTypeA.isOpen = false; $virtualCartTypeA.isOpenOrClose = function() { if (!$virtualCartTypeA.isOpen) { $virtualCartTypeA.displayView().openLoader(); $virtualCartTypeA.load(); $virtualCartTypeA.isOpen = true; console.log("virtualCartTypeA : case : Opening.."); $virtualCartTypeA.displayView().open(); } else { $virtualCartTypeA.isOpen = false; console.log("virtualCartTypeA : case : Closeing.."); $virtualCartTypeA.displayView().closePromotion(); $virtualCartTypeA.displayView().close(); } } /* Open */ /* getUrlCheckout */ $virtualCartTypeA.getUrlCheckout = function() { var strUrl = GURL.base_url(); var strRetrun = 'checkout?pdata='; var strArray = []; $.each($('.view-item-container-type-a .view-item-type-a .cover-product'), function(k, item) { var note = ($(this).attr('data-note') != "") ? $(this).attr('data-note').replace(/-/g, '+') : ""; strArray.push($(this).attr('data-id') + '-' + parseFloat($(this).find('.qty').text()) + '-' + note); }); var strCartId = ''; if ($virtualCartTypeA.is_note_exist && typeof store.get('gae_cart_id') !== 'undefined' && store.get('gae_cart_id') != "") { strCartId = '&txt_cart_id=' + store.get('gae_cart_id'); } var strPromotion = ''; if ($virtualCartTypeA.PromotionId != "0") { strPromotion = '&promotion_id=' + $virtualCartTypeA.PromotionId; } var sumUrl = strUrl + strRetrun + strArray.join(',') + strPromotion + strCartId; console.log("$virtualCartTypeA.getUrlCheckout : sumUrl : ", sumUrl); return sumUrl; }; /* getUrlCheckout */ /* Checkout */ $virtualCartTypeA.virCheckout = function() { var total = $virtualCartTypeA.displayView().totalItems(); var statusLoader = $virtualCartTypeA.displayView().getStatusLoader(); if (!statusLoader) { console.log("$virtualCartTypeA.virCheckout : statusLoader: ", statusLoader); if (total <= 0) { console.log("$virtualCartTypeA.virCheckout : total: ", total); return false; } else { return window.location.href = $virtualCartTypeA.getUrlCheckout(); console.log("$virtualCartTypeA.virCheckout : total: ", total); } } else { console.log("$virtualCartTypeA.virCheckout : statusLoader: ", statusLoader); } } /* Checkout */ $(function() { var shopId = parseFloat(CUR_THEME.shop_id()); switch (shopId) { /* support language ('en','th') */ case 409: var language = 'en'; var iconOpen = $virtualCartTypeA.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeA.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconNone = $virtualCartTypeA.icnPath + 'icnt_outline_cart01_light@2x.png'; var textNone = "ยังไม่มีสินค้าในรถเข็น"; $virtualCartTypeA.install(language, shopId, iconOpen, iconClose, iconNone, textNone); break; case 413: var language = 'en'; var iconOpen = $virtualCartTypeA.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeA.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconNone = $virtualCartTypeA.icnPath + 'icnt_outline_cart01_light@2x.png'; var textNone = "ยังไม่มีสินค้าในรถเข็น"; $virtualCartTypeA.install(language, shopId, iconOpen, iconClose, iconNone, textNone); break; /* case 500: var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_basket01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconNone = 'https://image.getappeasy.com/src/images/2000/1118/0812/118812t1528466774.png'; var textNone = "ยังไม่มีเมนูในตะกร้า"; $virtualCartTypeA.install(language, shopId, iconOpen, iconClose, iconNone, textNone); break; */ /* case 635: var language = 'en'; var iconOpen = $virtualCartTypeA.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeA.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconNone = $virtualCartTypeA.icnPath + 'icnt_emptycart_outline01_light@2x.png'; var textNone = "ยังไม่มีสินค้าในรถเข็น"; $virtualCartTypeA.install(language, shopId, iconOpen, iconClose, iconNone, textNone); break; */ case 737: var language = 'en'; var iconOpen = $virtualCartTypeA.icnPath + 'icnt_fill_cart03_dark@2x.png'; var iconClose = $virtualCartTypeA.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconNone = $virtualCartTypeA.icnPath + 'icnt_fill_cart03_light@2x.png'; var textNone = "ยังไม่มีสินค้าในรถเข็น"; $virtualCartTypeA.install(language, shopId, iconOpen, iconClose, iconNone, textNone); break; case 774: var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_light@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconNone = 'https://image.getappeasy.com/src/images/2000/1118/0812/118812t1528466774.png'; var textNone = "ยังไม่มีเมนูในตะกร้า"; $virtualCartTypeA.install(language, shopId, iconOpen, iconClose, iconNone, textNone); break; default: break; } });/* Cart displat at right side of page */ var $virtualCartTypeB = {}; /* params */ $virtualCartTypeB.path = CUR_THEME.devsource_url() + "dev.sugarfree/share/componentVirtualCartTypeB/"; $virtualCartTypeB.icnPath = CUR_THEME.extensions_url() + '../../assets/'; $virtualCartTypeB.templateRoot = 'root.php'; $virtualCartTypeB.templateProduct = 'products.php'; $virtualCartTypeB.templateProductPromotion = 'promotion.php'; $virtualCartTypeB.api = GURL.base_api_url(); $virtualCartTypeB.languageData = false; $virtualCartTypeB.urlCheckout = ''; $virtualCartTypeB.indexCout = 0; $virtualCartTypeB.shopId = 0; $virtualCartTypeB.PromotionId = 0; $virtualCartTypeB.language = 'en'; Number.prototype.format = function(n, x) { var re = '\\d(?=(\\d{' + (x || 3) + '})+' + (n > 0 ? '\\.' : '$') + ')'; return this.toFixed(Math.max(0, ~~n)).replace(new RegExp(re, 'g'), '$&,'); }; /* set language */ $virtualCartTypeB.setLanguage = function(language) { var language_data = { en: { order: 'Order Summary ', checkout: 'CHECKOUT', continued: 'BUY MORE', shopping: 'Shopping Cart', empty: 'Your cart is empty', save: 'Save', shipping: 'Shipping*', tax: 'Tax*', estimated: 'ESTIMATED TOTAL*', currency: 'THB', buy: 'ซื้ออีก', discount: 'จะได้ส่วนลดรวมเป็น', getdiscount: 'ได้ส่วนลด', percent: '%', }, th: { order: 'สรุปรายการสั่งซื้อ', checkout: 'ไปขั้นตอนการสั่งซื้อและชำระเงิน ', continued: 'เลือกซื้อรายการอื่น', shopping: 'รายการสั่งซื้อ', empty: 'ยังไม่มีรายการ', save: 'ลด', shipping: 'ค่าจัดส่ง*', tax: 'ภาษี*', estimated: 'ยอดที่ต้องจ่ายโดยประมาณ', currency: 'บาท', buy: 'ซื้ออีก', discount: 'จะได้ส่วนลดรวมเป็น', getdiscount: 'ได้ส่วนลด', percent: '%', } }; switch (language) { case 'en': return language_data.en; break; case 'th': return language_data.th; break; default: return language_data.en; break; } }; /* Install */ $virtualCartTypeB.install = function(language, shopId, iconOpen, iconClose, iconEmpty) { $virtualCartTypeB.language = (language != '' || language != undefined)? language: 'en'; if (window.location.href.indexOf('/checkout') == -1 && window.location.href.indexOf('/login') == -1 && window.location.href.indexOf('/thankyou') == -1 && window.location.href.indexOf('/fail') == -1) { $virtualCartTypeB.languageData = $virtualCartTypeB.setLanguage(language); $virtualCartTypeB.shopId = shopId; /* dont install in (viewcart) */ var rootVirtualCart = $('#root-virtual-cart-type-b'); if (!rootVirtualCart.length) { $.get($virtualCartTypeB.path + 'componentVirtualCartTypeB.css', function(response) { $('head').append(''); }); $.get($virtualCartTypeB.path + $virtualCartTypeB.templateRoot, { languageData: $virtualCartTypeB.languageData, imgpath: this.icnPath, iconOpen: iconOpen, iconClose: iconClose, iconEmpty: iconEmpty, shopId: shopId, path: $virtualCartTypeB.path }, function(response) { $('body').append(response); }); } } else {} }; /* Install */ /* Display */ $virtualCartTypeB.displayView = function() { var display = { cartContainer: function() { var cart = $('#root-virtual-cart-type-b.virtual-view-container-type-b'); return cart; }, cartContainerStatus: function(status) { var cart = $virtualCartTypeB.displayView().cartContainer(); return cart.hasClass(status); }, cartContainerAddStatus: function(status) { $virtualCartTypeB.displayView().cartContainer().addClass(status); var body = $('body'); if ($(window).width() <= 676) { body.css({ 'position': 'relative', 'overflow': 'hidden' }); } }, cartContainerRemoveStatus: function(status) { $virtualCartTypeB.displayView().cartContainer().removeClass(status); var body = $('body'); body.css({ 'position': 'relative', 'overflow': 'auto' }); }, loaderCart: function() { var loader = $('#root-virtual-cart-type-b.virtual-view-container-type-b .loader-type-b'); return loader; }, loaderCartStatus: function(status) { var loader = $virtualCartTypeB.displayView().loaderCart(); return loader.hasClass(status); }, loaderCartAddStatus: function(status) { var loader = $virtualCartTypeB.displayView().loaderCart(); if (!loader.hasClass(status)) { loader.addClass(status); } }, loaderCartRemoveStatus: function(status) { var loader = $virtualCartTypeB.displayView().loaderCart(); if (loader.hasClass(status)) { loader.removeClass(status); } }, topOrderContainer: function() { var top = $('#root-virtual-cart-type-b.virtual-view-container-type-b .top-type-b .cover-text .order'); return top; }, topOrderStatus: function(status) { var topOrder = $virtualCartTypeB.displayView().topOrderContainer(); return topOrder.hasClass(status); }, topOrderAddStatus: function(status) { var topOrder = $virtualCartTypeB.displayView().topOrderContainer(); if (!topOrder.hasClass(status)) { topOrder.addClass(status); } }, topOrderRemoveStatus: function(status) { var topOrder = $virtualCartTypeB.displayView().topOrderContainer(); if (topOrder.hasClass(status)) { topOrder.removeClass(status); } }, topEmptyContainer: function() { var topEmpty = $('#root-virtual-cart-type-b.virtual-view-container-type-b .top-type-b .cover-text .shopping'); return topEmpty; }, topEmptyStatus: function(status) { var topEmpty = $virtualCartTypeB.displayView().topEmptyContainer(); return topEmpty.hasClass(status); }, topEmptyAddStatus: function(status) { var topEmpty = $virtualCartTypeB.displayView().topEmptyContainer(); if (!topEmpty.hasClass(status)) { topEmpty.addClass(status); } }, topEmptyRemoveStatus: function(status) { var topEmpty = $virtualCartTypeB.displayView().topEmptyContainer(); if (topEmpty.hasClass(status)) { topEmpty.removeClass(status); } }, topChekoutContainer: function() { var topChekout = $('#root-virtual-cart-type-b.virtual-view-container-type-b .top-type-b .cover-button'); return topChekout; }, topChekoutChekout: function(chekout) { var topChekout = $virtualCartTypeB.displayView().topChekoutContainer(); return topChekout.html(chekout); }, topChekoutStatus: function(status) { var topChekout = $virtualCartTypeB.displayView().topChekoutContainer(); return topChekout.hasClass(status); }, topChekoutAddStatus: function(status) { var topChekout = $virtualCartTypeB.displayView().topChekoutContainer(); if (!topChekout.hasClass(status)) { topChekout.addClass(status); } }, topChekoutRemoveStatus: function(status) { var topChekout = $virtualCartTypeB.displayView().topChekoutContainer(); if (topChekout.hasClass(status)) { topChekout.removeClass(status); } }, bodyCover: function() { var body_cover = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b'); return body_cover; }, bodyCoverStatus: function(status) { var body_cover = $virtualCartTypeB.displayView().bodyCover(); return body_cover.hasClass(status); }, bodyCoverAddStatus: function(status) { var body_cover = $virtualCartTypeB.displayView().bodyCover(); if (!body_cover.hasClass(status)) { body_cover.addClass(status); } }, bodyCoverRemoveStatus: function(status) { var body_cover = $virtualCartTypeB.displayView().bodyCover(); if (body_cover.hasClass(status)) { body_cover.removeClass(status); } }, bodyPromotions: function() { var cover_promotions = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-promotions-type-b'); return cover_promotions; }, bodyPromotionsStatus: function(status) { var cover_promotions = $virtualCartTypeB.displayView().bodyPromotions(); return cover_promotions.hasClass(status); }, bodyPromotionsAddStatus: function(status) { var cover_promotions = $virtualCartTypeB.displayView().bodyPromotions(); if (!cover_promotions.hasClass(status)) { cover_promotions.addClass(status); } }, bodyPromotionsRemoveStatus: function(status) { var cover_promotions = $virtualCartTypeB.displayView().bodyPromotions(); if (cover_promotions.hasClass(status)) { cover_promotions.removeClass(status); } }, bodyPromotionsTextUpdate: function(text) { var cover_promotions_text = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-promotions-type-b .cover-text'); cover_promotions_text.find('.text').text(text); }, bodyPromotionsText: function() { var cover_promotions_text = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-promotions-type-b .cover-text'); return cover_promotions_text; }, bodyPromotionsTextAddStatus: function(status) { var cover_promotions_text = $virtualCartTypeB.displayView().bodyPromotionsText(); if (!cover_promotions_text.hasClass(status)) { cover_promotions_text.addClass(status); } }, bodyPromotionsTextRemoveStatus: function(status) { var cover_promotions_text = $virtualCartTypeB.displayView().bodyPromotionsText(); if (cover_promotions_text.hasClass(status)) { cover_promotions_text.removeClass(status); } }, bodyPromotionsGaugeUpdate: function(percent) { var cover_promotions_gauge = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-promotions-type-b .cover-gauge .gauge'); cover_promotions_gauge.css('width', percent + '%'); }, bodyPromotionsGauge: function() { var cover_promotions_gauge = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-promotions-type-b .cover-gauge'); return cover_promotions_gauge; }, bodyPromotionsGaugeAddStatus: function(status) { var cover_promotions_gauge = $virtualCartTypeB.displayView().bodyPromotionsGauge(); if (!cover_promotions_gauge.hasClass(status)) { cover_promotions_gauge.addClass(status); } }, bodyPromotionsGaugeRemoveStatus: function(status) { var cover_promotions_gauge = $virtualCartTypeB.displayView().bodyPromotionsGauge(); if (cover_promotions_gauge.hasClass(status)) { cover_promotions_gauge.removeClass(status); } }, bodyPromotionsPricesUpdate: function(status, price) { var cover_promotions_price = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-promotions-type-b .cover-price'); cover_promotions_price.find('#' + status).text(price); }, bodyPromotionsPrices: function() { var cover_promotions_prices = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-promotions-type-b .cover-price'); return cover_promotions_prices; }, bodyPromotionsPricesAddStatus: function(status) { var cover_promotions_prices = $virtualCartTypeB.displayView().bodyPromotionsPrices(); if (!cover_promotions_prices.hasClass(status)) { cover_promotions_prices.addClass(status); } }, bodyPromotionsPricesRemoveStatus: function(status) { var cover_promotions_prices = $virtualCartTypeB.displayView().bodyPromotionsPrices(); if (cover_promotions_prices.hasClass(status)) { cover_promotions_prices.removeClass(status); } }, bodyProducts: function() { var cover_products = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-products-type-b'); return cover_products; }, bodyProductsReset: function() { $virtualCartTypeB.displayView().bodyProducts().html(''); }, bodyProductsStatus: function(status) { var cover_products = $virtualCartTypeB.displayView().bodyProducts(); return cover_products.hasClass(status); }, bodyProductsAddStatus: function(status) { var cover_products = $virtualCartTypeB.displayView().bodyProducts(); if (!cover_products.hasClass(status)) { cover_products.addClass(status); } }, bodyProductsRemoveStatus: function(status) { var cover_products = $virtualCartTypeB.displayView().bodyProducts(); if (cover_products.hasClass(status)) { cover_products.removeClass(status); } }, bodyProductsId: function(product_id, qty) { var cover_products = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-products-type-b .cover-product[data-id="' + product_id + '"][data-index="' + qty + '"]'); return cover_products; }, bodyPrices: function() { var cover_prices = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-price-type-b'); return cover_prices; }, bodyPricesStatus: function(status) { var cover_prices = $virtualCartTypeB.displayView().bodyPrices(); return cover_prices.hasClass(status); }, bodyPricesAddStatus: function(status) { var cover_prices = $virtualCartTypeB.displayView().bodyPrices(); if (!cover_prices.hasClass(status)) { cover_prices.addClass(status); } }, bodyPricesRemoveStatus: function(status) { var cover_prices = $virtualCartTypeB.displayView().bodyPrices(); if (cover_prices.hasClass(status)) { cover_prices.removeClass(status); } }, bodyPricesUpdate: function(status, price) { var cover_prices = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-price-type-b .cover-main .cover-price .cover-data .right .price'); cover_prices.find('#' + status).text(price); }, bodyNote: function() { var cover_note = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-note-type-b'); return cover_note; }, bodyNoteStatus: function(status) { var cover_note = $virtualCartTypeB.displayView().bodyNote(); return cover_note.hasClass(status); }, bodyNoteAddStatus: function(status) { var cover_note = $virtualCartTypeB.displayView().bodyNote(); if (!cover_note.hasClass(status)) { cover_note.addClass(status); } }, bodyNoteRemoveStatus: function(status) { var cover_note = $virtualCartTypeB.displayView().bodyNote(); if (cover_note.hasClass(status)) { cover_note.removeClass(status); } }, bodyContinued: function() { var cover_continued = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-continued-type-b'); return cover_continued; }, bodyContinuedStatus: function(status) { var cover_continued = $virtualCartTypeB.displayView().bodyContinued(); return cover_continued.hasClass(status); }, bodyContinuedAddStatus: function(status) { var cover_continued = $virtualCartTypeB.displayView().bodyContinued(); if (!cover_continued.hasClass(status)) { cover_continued.addClass(status); } }, bodyContinuedRemoveStatus: function(status) { var cover_continued = $virtualCartTypeB.displayView().bodyContinued(); if (cover_continued.hasClass(status)) { cover_continued.removeClass(status); } }, bodyProductsNull: function() { var view_body = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-products-null-type-b'); return view_body; }, bodyProductsNullStatus: function(status) { var view_body = $virtualCartTypeB.displayView().bodyProductsNull(); return view_body.hasClass(status); }, bodyProductsNullAddStatus: function(status) { var view_body = $virtualCartTypeB.displayView().bodyProductsNull(); if (!view_body.hasClass(status)) { view_body.addClass(status); } }, bodyProductsNullRemoveStatus: function(status) { var view_body = $virtualCartTypeB.displayView().bodyProductsNull(); if (view_body.hasClass(status)) { view_body.removeClass(status); } }, bodyProductsEmptyNull: function() { var view_body = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-products-empty-null-type-b'); return view_body; }, bodyProductsEmptyNullStatus: function(status) { var view_body = $virtualCartTypeB.displayView().bodyProductsEmptyNull(); return view_body.hasClass(status); }, bodyProductsEmptyNullAddStatus: function(status) { var view_body = $virtualCartTypeB.displayView().bodyProductsEmptyNull(); if (!view_body.hasClass(status)) { view_body.addClass(status); } }, bodyProductsEmptyNullRemoveStatus: function(status) { var view_body = $virtualCartTypeB.displayView().bodyProductsEmptyNull(); if (view_body.hasClass(status)) { view_body.removeClass(status); } }, bodyContinuedNull: function() { var view_body = $('#root-virtual-cart-type-b.virtual-view-container-type-b .body-type-b .view-continued-null-type-b'); return view_body; }, bodyContinuedNullStatus: function(status) { var view_body = $virtualCartTypeB.displayView().bodyContinuedNull(); return view_body.hasClass(status); }, bodyContinuedNullAddStatus: function(status) { var view_body = $virtualCartTypeB.displayView().bodyContinuedNull(); if (!view_body.hasClass(status)) { view_body.addClass(status); } }, bodyContinuedNullRemoveStatus: function(status) { var view_body = $virtualCartTypeB.displayView().bodyContinuedNull(); if (view_body.hasClass(status)) { view_body.removeClass(status); } }, consoleLog: function(statu, data) { var statuConsole = true; if (statuConsole) { console.log(statu, data); } }, }; return display; }; /* Display */ /* getCart */ $virtualCartTypeB.storeStatus = function(storeIn) { var status = false; if (typeof storeIn != 'undefined') { status = true; } return status; }; $virtualCartTypeB.storeStatusGaeCartId = function(storeIn) { var status = false; if (typeof storeIn.get('gae_cart_id') != 'undefined') { status = true; } return status; }; $virtualCartTypeB.getCart = function(callback) { var getCartTime = setTimeout(function() { var dataSend = {}; if ($virtualCartTypeB.storeStatus(store) && $virtualCartTypeB.storeStatusGaeCartId(store)) { dataSend.txt_cart_id = parseFloat(store.get('gae_cart_id')); } $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getCart : dataSend : ", dataSend); GAEAPI.get('cart/current', dataSend).then(function(output) { window.clearTimeout(getCartTime); var currentCart = output.data; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getCart : currentCart : ", currentCart); callback(currentCart); }); }, 500); }; $virtualCartTypeB.cartRowArray = function(cart_row_array, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : cartRowArray : cart_row_array : ", cart_row_array); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : cartRowArray : cart_row_array.length : ", cart_row_array.length); var cartRowArrayStatus = true; for (var i = 0; cart_row_array.length > i; i++) { $virtualCartTypeB.products().updateProductId(cart_row_array[i].object_id, cart_row_array[i].amount, function(dataAddProductId) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : cartRowArray : addProductId : dataAddProductId : ", dataAddProductId); }); } callback(cartRowArrayStatus); }; $virtualCartTypeB.statusGetCart = { promotion: { load: false, done: false } }; $virtualCartTypeB.getCartPromotion = function(callback) { var getCartPromotionTime = 0; var dataSend = {}; if ($virtualCartTypeB.storeStatus(store) && $virtualCartTypeB.storeStatusGaeCartId(store)) { dataSend.txt_cart_id = parseFloat(store.get('gae_cart_id')); } $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getCartPromotion : dataSend : ", dataSend); GAEAPI.get('cart/current', dataSend).then(function(output) { getCartPromotionTime = setTimeout(function() { window.clearTimeout(getCartPromotionTime); var currentCartPromotion = output.data; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getCartPromotion : currentCartPromotion : ", currentCartPromotion); callback(currentCartPromotion); }, 100); }); }; $virtualCartTypeB.getCartPromotionAdd = function(promotion_id, cart_id, clear_promotion, callback) { var promotion_add = {}; if (promotion_id != "0") { var dataSend = { 'txt_promotion_id': parseFloat(promotion_id), 'txt_cart_id': parseFloat(cart_id), 'txt_clear_promotion': parseFloat(clear_promotion) }; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getCartPromotionAdd : dataSend : ", dataSend); GAEAPI.get('cart/cart_promotion_save', dataSend).then(function(output) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getCartPromotionAdd : output : ", output); var getCartPromotionAddTime = setTimeout(function() { window.clearTimeout(getCartPromotionAddTime); if (output.ok == 1) { promotion_add = output; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getCartPromotionAdd : promotion_add : ", promotion_add); } callback(promotion_add); }, 10); }); } else { callback(promotion_add); } }; $virtualCartTypeB.postCartPromotionDelete = function(promotion_id, cart_id, callback) { var dataSend = { 'txt_promotion_id': parseFloat(promotion_id), 'txt_cart_id': parseFloat(cart_id) }; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getCartPromotionDelete : dataSend : ", dataSend); GAEAPI.post('cart/cart_promotion_delete', dataSend).then(function(output) { var postCartPromotionDeleteTime = setTimeout(function() { window.clearTimeout(postCartPromotionDeleteTime); if (output.ok == 1) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getCartPromotionDelete : output : ", output); } callback(output); }, 10); }); }; $virtualCartTypeB.checkLifetime = function(promotion_lifetime) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : checkLifetime : promotion_lifetime : ", promotion_lifetime); var status = true; if (promotion_lifetime.lifetime_end_time != "-1") { status = moment.unix(promotion_lifetime.lifetime_end_time) > moment.now(); } return status; }; $virtualCartTypeB.controlPromotions = function(promotions, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotions : promotions : ", promotions); var control_promotions_status = false; if (promotions.length) { control_promotions_status = true; callback(control_promotions_status); } else { control_promotions_status = false; callback(control_promotions_status); } }; $virtualCartTypeB.controlPromotionsCart = function(cart, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotionsCart : cart : ", cart); var control_promotions_cart_status = false; if (cart.cart_promotion.length) { control_promotions_cart_status = true; callback(control_promotions_cart_status); } else { control_promotions_cart_status = false; callback(control_promotions_cart_status); } }; $virtualCartTypeB.checkPromotionsCartTypeSix = function(cart, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotionsCartDelete : cart : ", cart); var check_promotions_cart_type_six_status = 0; for (var i = 0; i < cart.cart_promotion.length; i++) { if (cart.cart_promotion[i].promotion_type_number == '6') { check_promotions_cart_type_six_status++; } } callback(check_promotions_cart_type_six_status); }; $virtualCartTypeB.controlDeleteTypeSixPromotionsCart = function(cart, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlDeleteTypeSixPromotionsCart : cart : ", cart); for (var i = 0; i < cart.cart_promotion.length; i++) { if (cart.cart_promotion[i].promotion_type_number == '6') { $virtualCartTypeB.postCartPromotionDelete(cart.cart_promotion[i].promotion_id, cart.cart_id, function(output) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlDeleteTypeSixPromotionsCart : postCartPromotionDelete : output ", output); callback(output); }); } } }; $virtualCartTypeB.controlPromotionsToCart = function(promotions, cart, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotionsToCart : cart : ", cart); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotionsToCart : promotions : ", promotions); var control_promotions_to_cart = ""; $virtualCartTypeB.controlPromotions(promotions, function(control_promotions_status) { control_promotions_to_cart = "controlPromotions"; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotionsToCart : controlPromotions : control_promotions_status : ", control_promotions_status); if (control_promotions_status) { $virtualCartTypeB.updateStatus([{ name: "bodyPromotionsAddStatus", status: "show" }]); control_promotions_to_cart = control_promotions_to_cart + " " + "if"; $virtualCartTypeB.controlPromotionsCart(cart, function(control_promotions_cart_status) { control_promotions_to_cart = control_promotions_to_cart + " " + "controlPromotionsCart"; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotions : controlPromotionsCart : control_promotions_cart_status : ", control_promotions_cart_status); if (control_promotions_cart_status) { control_promotions_to_cart = control_promotions_to_cart + " " + "if"; $virtualCartTypeB.checkPromotionsCartTypeSix(cart, function(check_promotions_cart_type_six_status) { control_promotions_to_cart = control_promotions_to_cart + " " + "checkPromotionsCartTypeSix"; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotions : controlPromotionsCart : checkPromotionsCartTypeSix : check_promotions_cart_type_six_status : ", check_promotions_cart_type_six_status); if (check_promotions_cart_type_six_status > 0) { control_promotions_to_cart = control_promotions_to_cart + " " + "if"; $virtualCartTypeB.controlDeleteTypeSixPromotionsCart(cart, function(output) { control_promotions_to_cart = control_promotions_to_cart + " " + "controlDeleteTypeSixPromotionsCart"; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotions : controlPromotionsCart : checkPromotionsCartTypeSix : controlDeleteTypeSixPromotionsCart : output : ", output); callback(control_promotions_to_cart); }); } else { callback(control_promotions_to_cart); } }); } else { control_promotions_to_cart = control_promotions_to_cart + " " + "else"; $virtualCartTypeB.updateStatus([{ name: "bodyPromotionsRemoveStatus", status: "edit" }]); callback(control_promotions_to_cart); } }); } else { control_promotions_to_cart = control_promotions_to_cart + " " + "else"; $virtualCartTypeB.updateStatus([{ name: "bodyPromotionsRemoveStatus", status: "show" }, { name: "bodyPromotionsRemoveStatus", status: "edit" }]); $virtualCartTypeB.controlPromotionsCart(cart, function(control_promotions_cart_status) { control_promotions_to_cart = control_promotions_to_cart + " " + "controlPromotionsCart"; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotions : controlPromotionsCart : control_promotions_cart_status : ", control_promotions_cart_status); if (control_promotions_cart_status) { control_promotions_to_cart = control_promotions_to_cart + " " + "if"; $virtualCartTypeB.checkPromotionsCartTypeSix(cart, function(check_promotions_cart_type_six_status) { control_promotions_to_cart = control_promotions_to_cart + " " + "checkPromotionsCartTypeSix"; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotions : controlPromotionsCart : checkPromotionsCartTypeSix : check_promotions_cart_type_six_status : ", check_promotions_cart_type_six_status); if (check_promotions_cart_type_six_status > 0) { control_promotions_to_cart = control_promotions_to_cart + " " + "if"; $virtualCartTypeB.controlDeleteTypeSixPromotionsCart(cart, function(output) { control_promotions_to_cart = control_promotions_to_cart + " " + "controlDeleteTypeSixPromotionsCart"; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotions : controlPromotionsCart : checkPromotionsCartTypeSix : controlDeleteTypeSixPromotionsCart : output : ", output); callback(control_promotions_to_cart); }); } else { control_promotions_to_cart = control_promotions_to_cart + " " + "eles"; callback(control_promotions_to_cart); } }); } else { control_promotions_to_cart = control_promotions_to_cart + " " + "else"; callback(control_promotions_to_cart); } }); } $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : controlPromotionsToCart : control_promotions_to_cart : ", control_promotions_to_cart); }); }; $virtualCartTypeB.calculateCartPromotion = function(promotions, cart, callback) { $virtualCartTypeB.displayView().bodyPromotionsGaugeUpdate(0); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotion : promotions : ", promotions); promotions.sort(function(obj1, obj2) { return parseFloat(obj1.promotion_row_display.buy.order[0].price) - parseFloat(obj2.promotion_row_display.buy.order[0].price); }); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotion : promotions : sort : ", promotions); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotion : cart : ", cart); var promotion_id = "0"; var sum_total_price = parseFloat(cart.cart_total_product_price) - parseFloat(cart.cart_total_product_discount); var sum_total_product = cart.cart_row_array.length; var calculate_promotion_statu = { 'start_price': false, 'start_total_price': 0, 'end_price': false, 'end_total_price': 0 }; for (var i = 0; i < promotions.length; i++) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotion : start-price for : promotions : ", i); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotion : start-price for : promotions : ", promotions[i]); var type_promotion = parseFloat(promotions[i].promotion_type_number); var total_stock_promotion = promotions[i].promotion_total_stock; var total_amount = parseFloat(promotions[i].promotion_row_display.buy.order[0].amount); var total_price = parseFloat(promotions[i].promotion_row_display.buy.order[0].price); var lifetime = promotions[i].promotion_lifetime; /* start-price */ if (type_promotion == 6 && total_stock_promotion > 0 && total_amount <= sum_total_product && $virtualCartTypeB.checkLifetime(lifetime) && total_price <= sum_total_price) { calculate_promotion_statu.start_price = true; calculate_promotion_statu.start_total_price = total_price; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotion : start-price for : promotions[i] : if : ", promotions[i]); $virtualCartTypeB.displayView().bodyPromotionsPricesUpdate('start-price', calculate_promotion_statu.start_total_price.format(2)); promotion_id = promotions[i].promotion_id; } /* start-price */ /* end-price */ if (type_promotion == 6 && total_stock_promotion > 0 && total_amount <= sum_total_product && $virtualCartTypeB.checkLifetime(lifetime) && sum_total_price < total_price && !calculate_promotion_statu.end_price) { calculate_promotion_statu.end_price = true; calculate_promotion_statu.end_total_price = total_price; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotion : end-price for : promotions[i] : if : ", promotions[i]); $virtualCartTypeB.displayView().bodyPromotionsPricesUpdate('end-price', calculate_promotion_statu.end_total_price.format(2)); } /* end-price */ } if (!calculate_promotion_statu.start_price) { $virtualCartTypeB.displayView().bodyPromotionsPricesUpdate('start-price', 0); } if (!calculate_promotion_statu.end_price) { calculate_promotion_statu.end_total_price = calculate_promotion_statu.start_total_price; $virtualCartTypeB.displayView().bodyPromotionsPricesUpdate('end-price', calculate_promotion_statu.start_total_price.format(2)); } if (calculate_promotion_statu.start_total_price == calculate_promotion_statu.end_total_price) { for (var i = 0; i < promotions.length; i++) { var type_promotion = parseFloat(promotions[i].promotion_type_number); var total_stock_promotion = promotions[i].promotion_total_stock; var total_amount = parseFloat(promotions[i].promotion_row_display.buy.order[0].amount); var total_price = parseFloat(promotions[i].promotion_row_display.buy.order[0].price); var lifetime = promotions[i].promotion_lifetime; if (promotions.length > 1) { if (type_promotion == 6 && total_stock_promotion > 0 && total_amount <= sum_total_product && $virtualCartTypeB.checkLifetime(lifetime) && sum_total_price > total_price && i < promotions.length - 1) { $virtualCartTypeB.displayView().bodyPromotionsPricesUpdate('start-price', total_price.format(2)); } } else { $virtualCartTypeB.displayView().bodyPromotionsPricesUpdate('start-price', 0); } } } $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotion : calculate_promotion_statu : ", calculate_promotion_statu); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotion : promotion_id : ", promotion_id); callback(promotion_id); }; $virtualCartTypeB.calculateCartPromotionText = function(status, promotions, cart, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionText : promotions : ", promotions); promotions.sort(function(obj1, obj2) { return parseFloat(obj1.promotion_row_display.buy.order[0].price) - parseFloat(obj2.promotion_row_display.buy.order[0].price); }); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionText : promotions : sort : ", promotions); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionText : cart : ", cart); var sum_total_price = parseFloat(cart.cart_total_product_price) - parseFloat(cart.cart_total_product_discount); var sum_total_product = cart.cart_row_array.length; var calculate_promotion_statu = { 'start_price': false, 'start_total_price': 0, 'start_total_sale_percent': 0, 'start_total_sale_price': 0, 'end_price': false, 'end_total_price': 0, 'end_total_sale_percent': 0, 'end_total_sale_price': 0 }; for (var i = 0; i < promotions.length; i++) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionText : start-price for : promotions : ", i); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionText : start-price for : promotions : ", promotions[i]); var type_promotion = parseFloat(promotions[i].promotion_type_number); var total_stock_promotion = promotions[i].promotion_total_stock; var total_amount = parseFloat(promotions[i].promotion_row_display.buy.order[0].amount); var total_price = parseFloat(promotions[i].promotion_row_display.buy.order[0].price); var total_sale_percent = parseFloat(promotions[i].promotion_row_display.sub.order[0].percent); var total_sale_price = parseFloat(promotions[i].promotion_row_display.sub.order[0].price); var lifetime = promotions[i].promotion_lifetime; /* start-price */ if (type_promotion == 6 && total_stock_promotion > 0 && total_amount <= sum_total_product && $virtualCartTypeB.checkLifetime(lifetime) && total_price <= sum_total_price) { calculate_promotion_statu.start_price = true; calculate_promotion_statu.start_total_price = total_price; calculate_promotion_statu.start_total_sale_percent = total_sale_percent; calculate_promotion_statu.start_total_sale_price = total_sale_price; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionText : start-price for : promotions[i] : if : ", promotions[i]); } /* start-price */ /* end-price */ if (type_promotion == 6 && total_stock_promotion > 0 && total_amount <= sum_total_product && $virtualCartTypeB.checkLifetime(lifetime) && sum_total_price < total_price && !calculate_promotion_statu.end_price) { calculate_promotion_statu.end_price = true; calculate_promotion_statu.end_total_price = total_price; calculate_promotion_statu.end_total_sale_percent = total_sale_percent; calculate_promotion_statu.end_total_sale_price = total_sale_price; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionText : end-price for : promotions[i] : if : ", promotions[i]); } /* end-price */ } if (!calculate_promotion_statu.start_price) { calculate_promotion_statu.start_total_price = 0; } if (!calculate_promotion_statu.end_price) { calculate_promotion_statu.end_total_price = calculate_promotion_statu.start_total_price; } $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionText : calculate_promotion_statu : ", calculate_promotion_statu); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionText : $virtualCartTypeB.languageData : ", $virtualCartTypeB.languageData); var calculate_text = ""; if (status == 'apply') { if (calculate_promotion_statu.start_total_sale_percent != 0) { calculate_text = $virtualCartTypeB.languageData.getdiscount + ' ' + calculate_text + ' ' + calculate_promotion_statu.start_total_sale_percent.format(2) + ' ' + $virtualCartTypeB.languageData.percent; } else if (calculate_promotion_statu.start_total_price != 0) { calculate_text = $virtualCartTypeB.languageData.getdiscount + ' ' + calculate_text + ' ' + calculate_promotion_statu.start_total_sale_price.format(2) + ' ' + $virtualCartTypeB.languageData.currency; } } else if (status == 'applyto') { var calculate_price = calculate_promotion_statu.end_total_price - sum_total_price; if (calculate_promotion_statu.start_total_price < calculate_promotion_statu.end_total_price) { calculate_text = $virtualCartTypeB.languageData.buy; if (calculate_promotion_statu.end_total_sale_percent != 0) { calculate_text = calculate_text + ' ' + calculate_price.format(2) + ' ' + $virtualCartTypeB.languageData.currency + ' ' + $virtualCartTypeB.languageData.discount + ' ' + calculate_promotion_statu.end_total_sale_percent.format(2) + ' ' + $virtualCartTypeB.languageData.percent; } else if (calculate_promotion_statu.end_total_sale_price != 0) { calculate_text = calculate_text + ' ' + calculate_price.format(2) + ' ' + $virtualCartTypeB.languageData.currency + ' ' + $virtualCartTypeB.languageData.discount + ' ' + calculate_promotion_statu.end_total_sale_price.format(2) + ' ' + $virtualCartTypeB.languageData.currency; } } else { calculate_text = $virtualCartTypeB.languageData.getdiscount; if (calculate_promotion_statu.start_total_sale_percent != 0) { calculate_text = calculate_text + ' ' + calculate_promotion_statu.start_total_sale_percent.format(2) + ' ' + $virtualCartTypeB.languageData.percent; } else if (calculate_promotion_statu.start_total_price != 0) { calculate_text = calculate_text + ' ' + calculate_promotion_statu.start_total_sale_price.format(2) + ' ' + $virtualCartTypeB.languageData.currency; } } } callback(calculate_text); }; $virtualCartTypeB.calculateCartPromotionGauge = function(promotions, cart, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionGauge : promotions : ", promotions); promotions.sort(function(obj1, obj2) { return parseFloat(obj1.promotion_row_display.buy.order[0].price) - parseFloat(obj2.promotion_row_display.buy.order[0].price); }); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionGauge : promotions : sort : ", promotions); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionGauge : cart : ", cart); var sum_total_price = parseFloat(cart.cart_total_product_price) - parseFloat(cart.cart_total_product_discount); var sum_total_product = cart.cart_row_array.length; var calculate_promotion_statu = { 'start_price': false, 'start_total_price': 0, 'end_price': false, 'end_total_price': 0 }; for (var i = 0; i < promotions.length; i++) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionGauge : start-price for : promotions : ", i); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionGauge : start-price for : promotions : ", promotions[i]); var type_promotion = parseFloat(promotions[i].promotion_type_number); var total_stock_promotion = promotions[i].promotion_total_stock; var total_amount = parseFloat(promotions[i].promotion_row_display.buy.order[0].amount); var total_price = parseFloat(promotions[i].promotion_row_display.buy.order[0].price); var lifetime = promotions[i].promotion_lifetime; /* start-price */ if (type_promotion == 6 && total_stock_promotion > 0 && total_amount <= sum_total_product && $virtualCartTypeB.checkLifetime(lifetime) && total_price <= sum_total_price) { calculate_promotion_statu.start_price = true; calculate_promotion_statu.start_total_price = total_price; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionGauge : start-price for : promotions[i] : if : ", promotions[i]); } /* start-price */ /* end-price */ if (type_promotion == 6 && total_stock_promotion > 0 && total_amount <= sum_total_product && $virtualCartTypeB.checkLifetime(lifetime) && sum_total_price < total_price && !calculate_promotion_statu.end_price) { calculate_promotion_statu.end_price = true; calculate_promotion_statu.end_total_price = total_price; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionGauge : end-price for : promotions[i] : if : ", promotions[i]); } /* end-price */ } if (!calculate_promotion_statu.start_price) { calculate_promotion_statu.start_total_price = 0; } if (!calculate_promotion_statu.end_price) { calculate_promotion_statu.end_total_price = calculate_promotion_statu.start_total_price; } $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : calculateCartPromotionGauge : calculate_promotion_statu : ", calculate_promotion_statu); var phase_gauge = calculate_promotion_statu.end_total_price - calculate_promotion_statu.start_total_price; var calculate_gauge = calculate_promotion_statu.end_total_price - calculate_promotion_statu.start_total_price; if (calculate_gauge == 0) { calculate_gauge = 100; } else { calculate_gauge = sum_total_price - calculate_promotion_statu.start_total_price; calculate_gauge = calculate_gauge / phase_gauge; calculate_gauge = calculate_gauge * 100; } callback(calculate_gauge, calculate_promotion_statu); }; /* getCart */ /* getPromotions */ $virtualCartTypeB.getPromotions = function(callback) { var currentPromotions = []; var option = { 'txt_type_number': 6 }; var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_badge_id': 18, 'txt_filter_json': JSON.stringify(option) }; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getPromotions : dataSend : ", dataSend); GAEAPI.get('promotion/lists', dataSend).then(function(output) { var getPromotionsTime = setTimeout(function() { window.clearTimeout(getPromotionsTime); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getPromotions : output : ", output); if (output.ok == 1) { /* currentPromotions = output.data.dataList; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getPromotions : currentPromotions : ", currentPromotions); */ for (var i = 0; i < output.data.dataList.length; i++) { if (output.data.dataList[i].promotion_type_number == "6" && $virtualCartTypeB.checkLifetime(output.data.dataList[i].promotion_lifetime)) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getPromotions : for : if : output.data.dataList[i] : ", output.data.dataList[i]); currentPromotions.push(output.data.dataList[i]); } } } $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : getPromotions : currentPromotions : ", currentPromotions); callback(currentPromotions); }, 100); }); }; /* getPromotions */ /* checkDiscountArray */ $virtualCartTypeB.checkDiscountArray = function(product_id, cart_product_discount_array) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : checkDiscountArray : product_id : ", product_id); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : checkDiscountArray : cart_product_discount_array : ", cart_product_discount_array); var objArray = { 'discount_full_price': 0, 'discount_calculate': 0, 'discount_discount_price': 0 }; if (cart_product_discount_array.length > 0) { for (var i = 0; i < cart_product_discount_array.length; i++) { if (cart_product_discount_array[i].product_id == product_id) { var start_price = parseFloat(cart_product_discount_array[i].cart_product_discount_price[0].start_price); var discount_price = parseFloat(cart_product_discount_array[i].cart_product_discount_price[0].discount_price); objArray.discount_full_price = start_price.format(2); objArray.discount_calculate = (start_price - discount_price).format(2); objArray.discount_discount_price = discount_price.format(2); break; } } } return objArray; }; /* checkDiscountArray */ /* checkPromotion */ $virtualCartTypeB.checkPromotion = function(currentCart) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : checkPromotion : currentCart : ", currentCart); var products_array = currentCart.cart_row_array.length; /* var estimated_total_price = parseFloat(currentCart.cart_total_exit_price; */ var estimated_total_price = (((parseFloat(currentCart.cart_total_product_price) - parseFloat(currentCart.cart_total_order_discount)) - parseFloat(currentCart.cart_total_promotion_discount)) - parseFloat(currentCart.cart_total_product_discount)); return estimated_total_price; }; /* checkPromotion */ /* status */ $virtualCartTypeB.updateStatus = function(objArray) { for (var i = 0; i < objArray.length; i++) { var function_name = objArray[i].name; var status = objArray[i].status; if (function_name == "cartContainerAddStatus") { $virtualCartTypeB.displayView().cartContainerAddStatus(status); } else if (function_name == "cartContainerRemoveStatus") { $virtualCartTypeB.displayView().cartContainerRemoveStatus(status); } else if (function_name == "loaderCartAddStatus") { $virtualCartTypeB.displayView().loaderCartAddStatus(status); } else if (function_name == "loaderCartRemoveStatus") { $virtualCartTypeB.displayView().loaderCartRemoveStatus(status); } else if (function_name == "topOrderAddStatus") { $virtualCartTypeB.displayView().topOrderAddStatus(status); } else if (function_name == "topOrderRemoveStatus") { $virtualCartTypeB.displayView().topOrderRemoveStatus(status); } else if (function_name == "topEmptyAddStatus") { $virtualCartTypeB.displayView().topEmptyAddStatus(status); } else if (function_name == "topEmptyRemoveStatus") { $virtualCartTypeB.displayView().topEmptyRemoveStatus(status); } else if (function_name == "topChekoutAddStatus") { $virtualCartTypeB.displayView().topChekoutAddStatus(status); } else if (function_name == "topChekoutRemoveStatus") { $virtualCartTypeB.displayView().topChekoutRemoveStatus(status); } else if (function_name == "bodyCoverAddStatus") { $virtualCartTypeB.displayView().bodyCoverAddStatus(status); } else if (function_name == "bodyCoverRemoveStatus") { $virtualCartTypeB.displayView().bodyCoverRemoveStatus(status); } else if (function_name == "bodyPromotionsAddStatus") { $virtualCartTypeB.displayView().bodyPromotionsAddStatus(status); } else if (function_name == "bodyPromotionsRemoveStatus") { $virtualCartTypeB.displayView().bodyPromotionsRemoveStatus(status); } else if (function_name == "bodyPromotionsTextAddStatus") { $virtualCartTypeB.displayView().bodyPromotionsTextAddStatus(status); } else if (function_name == "bodyPromotionsTextRemoveStatus") { $virtualCartTypeB.displayView().bodyPromotionsTextRemoveStatus(status); } else if (function_name == "bodyPromotionsGaugeAddStatus") { $virtualCartTypeB.displayView().bodyPromotionsGaugeAddStatus(status); } else if (function_name == "bodyPromotionsGaugeRemoveStatus") { $virtualCartTypeB.displayView().bodyPromotionsGaugeRemoveStatus(status); } else if (function_name == "bodyPromotionsPricesAddStatus") { $virtualCartTypeB.displayView().bodyPromotionsPricesAddStatus(status); } else if (function_name == "bodyPromotionsPricesRemoveStatus") { $virtualCartTypeB.displayView().bodyPromotionsPricesRemoveStatus(status); } else if (function_name == "bodyProductsAddStatus") { $virtualCartTypeB.displayView().bodyProductsAddStatus(status); } else if (function_name == "bodyProductsRemoveStatus") { $virtualCartTypeB.displayView().bodyProductsRemoveStatus(status); } else if (function_name == "bodyPricesAddStatus") { $virtualCartTypeB.displayView().bodyPricesAddStatus(status); } else if (function_name == "bodyPricesRemoveStatus") { $virtualCartTypeB.displayView().bodyPricesRemoveStatus(status); } else if (function_name == "bodyNoteAddStatus") { $virtualCartTypeB.displayView().bodyNoteAddStatus(status); } else if (function_name == "bodyNoteRemoveStatus") { $virtualCartTypeB.displayView().bodyNoteRemoveStatus(status); } else if (function_name == "bodyContinuedAddStatus") { $virtualCartTypeB.displayView().bodyContinuedAddStatus(status); } else if (function_name == "bodyContinuedRemoveStatus") { $virtualCartTypeB.displayView().bodyContinuedRemoveStatus(status); } else if (function_name == "bodyProductsNullAddStatus") { $virtualCartTypeB.displayView().bodyProductsNullAddStatus(status); } else if (function_name == "bodyProductsNullRemoveStatus") { $virtualCartTypeB.displayView().bodyProductsNullRemoveStatus(status); } else if (function_name == "bodyProductsEmptyNullAddStatus") { $virtualCartTypeB.displayView().bodyProductsEmptyNullAddStatus(status); } else if (function_name == "bodyProductsEmptyNullRemoveStatus") { $virtualCartTypeB.displayView().bodyProductsEmptyNullRemoveStatus(status); } else if (function_name == "bodyContinuedNullAddStatus") { $virtualCartTypeB.displayView().bodyContinuedNullAddStatus(status); } else if (function_name == "bodyContinuedNullRemoveStatus") { $virtualCartTypeB.displayView().bodyContinuedNullRemoveStatus(status); } } }; /* status */ /* refresh */ $virtualCartTypeB.cart_product_discount_array = []; $virtualCartTypeB.Refresh = function() { $virtualCartTypeB.getPromotions(function(currentPromotions) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : getPromotions : currentPromotions : ", currentPromotions); $virtualCartTypeB.getCartPromotion(function(currentCartPromotion) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : getCartPromotion : currentCartPromotion : ", currentCartPromotion); if ($virtualCartTypeB.storeStatus(store)) { $virtualCartTypeB.controlPromotionsToCart(currentPromotions, currentCartPromotion, function(control_promotions_to_cart) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : controlPromotionsToCart : control_promotions_to_cart : ", control_promotions_to_cart); $virtualCartTypeB.calculateCartPromotion(currentPromotions, currentCartPromotion, function(promotion_id) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : controlPromotionsToCart : calculateCartPromotion : promotion_id : ", promotion_id); $virtualCartTypeB.getCartPromotionAdd(promotion_id, currentCartPromotion.cart_id, 0, function(promotion_add) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : controlPromotionsToCart : calculateCartPromotion : getCartPromotionAdd : promotion_add : ", promotion_add); $virtualCartTypeB.getCart(function(currentCart) { $virtualCartTypeB.cartRowArray(currentCart.cart_row_array, function(cartRowArrayStatus) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : controlPromotionsToCart : calculateCartPromotion : getCartPromotionAdd : promotion_add : cartRowArrayStatus : ", cartRowArrayStatus); $virtualCartTypeB.getCart(function(currentCart) { var shopId = $virtualCartTypeB.shopId; $virtualCartTypeB.updateStatus([{ name: "loaderCartAddStatus", status: "show" }, { name: "bodyCoverAddStatus", status: "show" }]); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : shopId : ", shopId); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : currentCart.cart_row_array.length : ", currentCart.cart_row_array.length); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : currentCart : ", currentCart); $virtualCartTypeB.cart_product_discount_array = currentCart.cart_product_discount_array; if (typeof currentCart != 'undefined' && currentCart.cart_row_array.length) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : ", "if"); $virtualCartTypeB.updateStatus([{ name: "topEmptyRemoveStatus", status: "show" }, { name: "bodyProductsNullRemoveStatus", status: "show" }, { name: "bodyProductsEmptyNullRemoveStatus", status: "show" }, { name: "bodyContinuedNullRemoveStatus", status: "show" }, { name: "topOrderAddStatus", status: "show" }, { name: "topChekoutAddStatus", status: "show" }, { name: "bodyProductsAddStatus", status: "show" }, { name: "bodyProductsAddStatus", status: "edit" }, { name: "bodyPricesAddStatus", status: "show" }, { name: "bodyPricesAddStatus", status: "edit" }, { name: "bodyNoteAddStatus", status: "show" }, { name: "bodyNoteAddStatus", status: "edit" }, { name: "bodyContinuedAddStatus", status: "show" }]); $virtualCartTypeB.urlCheckout = currentCart.cart_checkout_link; $virtualCartTypeB.displayView().bodyPricesUpdate("price-shipping", parseFloat(currentCart.cart_total_shipping_price).format(2)); $virtualCartTypeB.displayView().bodyPricesUpdate("price-tax", parseFloat(currentCart.cart_total_vat_price).format(2)); $virtualCartTypeB.displayView().bodyPricesUpdate("estimated-total", parseFloat($virtualCartTypeB.checkPromotion(currentCart)).format(2)); if ($virtualCartTypeB.storeStatus(store)) { store.set('gae_cart_id', currentCart.cart_id); } $virtualCartTypeB.displayView().bodyProductsReset(); var displayProduct = $virtualCartTypeB.displayView().bodyProducts(); if ($virtualCartTypeB.displayView().bodyProductsStatus("edit")) { for (var i = 0; i < currentCart.cart_row_array.length; i++) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : cart_row_array : item ", i); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : cart_row_array : product_id : ", currentCart.cart_row_array[i].object_id); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : cart_row_array : data : ", currentCart.cart_row_array[i]); var item = currentCart.cart_row_array[i]; var product_id = item.object_id || item.product_id; var product_qtn = item.cart_row_display.amount; var product_compare_price = 0; var product_price = parseFloat(item.cart_row_display.unit_exit_price); var product_title = item.cart_row_display.title; var product_image = (item.cart_row_display.image_array.length) ? item.cart_row_display.image_array[0].image_url : ''; var isOption = (item.cart_row_display.variant_name != '') ? true : false; var dataSend = { shopId: shopId, product_id: product_id, product_qtn: product_qtn, product_compare_price: product_compare_price, product_price: product_price.format(2), product_title: product_title, product_image: product_image, languageData: $virtualCartTypeB.languageData, imgpath: $virtualCartTypeB.icnPath, idx: item.cart_row_id, option_name: (isOption) ? item.cart_row_display.variant_name : '', note: item.note, discount: $virtualCartTypeB.checkDiscountArray(product_id, currentCart.cart_product_discount_array) }; var template = ''; if (parseFloat(item.is_promotion_item) == 1) { template = $virtualCartTypeB.templateProductPromotion; } else { template = $virtualCartTypeB.templateProduct; } $.post($virtualCartTypeB.path + template, dataSend, function(data) { displayProduct.append(data); }); } } } else { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : ", "else"); $virtualCartTypeB.displayView().bodyProductsReset(); $virtualCartTypeB.updateStatus([{ name: "topOrderRemoveStatus", status: "show" }, { name: "topChekoutRemoveStatus", status: "show" }, { name: "bodyPromotionsRemoveStatus", status: "show" }, { name: "bodyProductsRemoveStatus", status: "show" }, { name: "bodyPricesRemoveStatus", status: "show" }, { name: "bodyNoteRemoveStatus", status: "show" }, { name: "bodyContinuedRemoveStatus", status: "show" }, { name: "topEmptyAddStatus", status: "show" }, { name: "bodyProductsNullAddStatus", status: "show" }, { name: "bodyProductsEmptyNullAddStatus", status: "show" }, { name: "bodyContinuedNullAddStatus", status: "show" }]); } $virtualCartTypeB.updateStatus([{ name: "loaderCartRemoveStatus", status: "show" }, { name: "bodyPromotionsRemoveStatus", status: "edit" }, { name: "bodyProductsRemoveStatus", status: "edit" }, { name: "bodyPricesRemoveStatus", status: "edit" }, { name: "bodyNoteRemoveStatus", status: "edit" }]); $virtualCartTypeB.calculateCartPromotionGauge(currentPromotions, currentCart, function(calculate_gauge, calculate_promotion_statu) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : calculateCartPromotionGauge : calculate_gauge : ", calculate_gauge); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : calculateCartPromotionGauge : calculate_promotion_statu : ", calculate_promotion_statu); $virtualCartTypeB.calculateCartPromotionText('apply', currentPromotions, currentCart, function(calculate_text) { /* apply */ var apply = setInterval(function() { window.clearInterval(apply); $virtualCartTypeB.displayView().bodyPromotionsTextUpdate(calculate_text); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : calculateCartPromotionText : apply calculate_text : ", calculate_text); }, 1000); $virtualCartTypeB.calculateCartPromotionText('applyto', currentPromotions, currentCart, function(calculate_text) { /* applyto */ $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : Refresh : calculateCartPromotionText : applyto calculate_text : ", calculate_text); var applyto = setInterval(function() { window.clearInterval(applyto); $virtualCartTypeB.displayView().bodyPromotionsTextUpdate(calculate_text); if (calculate_gauge < 100) { $virtualCartTypeB.displayView().bodyPromotionsGaugeUpdate(calculate_gauge); } else { $virtualCartTypeB.displayView().bodyPromotionsGaugeUpdate(calculate_gauge); } }, 2000); }); }); }); }); }); }); }); }); }); } }); }); }; /* refresh */ /* timeFunctiond */ /* $virtualCartTypeB.timeFunctiond = function() { var timeFunctiond = { consoleLog: function(name, data) { console.log(name, data); }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("loopTime getData : ", "------- dataSend -------"); _self.consoleLog("loopTime getData : api : ", api); _self.consoleLog("loopTime getData : dataSend : ", dataSend); _self.consoleLog("loopTime getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend).then(function(output) { _self.consoleLog("loopTime getData : ", "------- getApi -------"); _self.consoleLog("loopTime getData : api : ", api); _self.consoleLog("loopTime getData : dataSend : ", dataSend); _self.consoleLog("loopTime getData : output : ", output); _self.consoleLog("loopTime getData : ", "------- getApi -------"); callback(output); }); }, momentUnix: function(callback) { var now = moment().unix(); callback(now); }, countdown: function(number, countdown, callback) { var _self = this; var timeCountdown = countdown.end - countdown.now; var duration = moment.duration(timeCountdown * 1000, "milliseconds"); if (timeCountdown > 0) { callback(number, duration, true); } else { callback(number, duration, false); } }, countdownArray: function(now, countdown, callback) { var _self = this; if (countdown.length != 0) { for (var i = 0; i < countdown.length; i++) { countdown[i].now = now; _self.countdown(i, countdown[i], function(number, duration, show) { countdown[number].day = (duration.days() <= 9) ? '0' + duration.days() : duration.days(); countdown[number].month = (duration.months() <= 9) ? '0' + duration.months() : duration.months(); countdown[number].year = (duration.years() <= 9) ? '0' + duration.years() : duration.years(); countdown[number].hours = (duration.hours() <= 9) ? '0' + duration.hours() : duration.hours(); countdown[number].minutes = (duration.minutes() <= 9) ? '0' + duration.minutes() : duration.minutes(); countdown[number].seconds = (duration.seconds() <= 9) ? '0' + duration.seconds() : duration.seconds(); countdown[number].show = show; if ((i + 1) == countdown.length) { callback(countdown); } }); } } else { callback(countdown); } }, loopTime: function() { var _self = this; var shopId = parseFloat(CUR_THEME.shop_id()); if (shopId == 495) { var timeout_promise = setTimeout(function() { _self.momentUnix(function(now) { _self.consoleLog("loopTime : ", now); _self.consoleLog("loopTime : cart_product_discount_array : ", $virtualCartTypeB.cart_product_discount_array); for (var i = 0; i < $virtualCartTypeB.cart_product_discount_array.length; i++) { var dataSend = { 'txt_product_id': $virtualCartTypeB.cart_product_discount_array[i].product_id }; _self.dataSend('product/discount', dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.consoleLog("loopTime : timeFunctiond : getApi : output : ", output); if (output.data.length == 0) { $virtualCartTypeB.products().removeProduct(dataSend.txt_product_id, 0) } }); }); } _self.loopTime(); }); }, 10000); } } }; return timeFunctiond; }; $virtualCartTypeB.timeFunctiond().loopTime(); */ /* timeFunctiond */ /* quantity */ $virtualCartTypeB.products = function() { var products = { checkProduct: function(product_id, callback) { var dataSend = { 'txt_product_id': product_id }; $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : checkProduct : dataSend : ", dataSend); GAEAPI.get('product/id', dataSend).then(function(output) { var getProductIdTime = setTimeout(function() { window.clearTimeout(getProductIdTime); var product_stock = 0; if (output.ok == 1) { product_stock = output.data.product_total_stock; } callback(product_stock); }, 100); }); }, updateProductId: function(product_id, quantity, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : addProductId : product_id : ", product_id); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : addProductId : quantity : ", quantity); var dataAddProductId = true; UiCart.delegate.product.updateAmount(product_id, quantity); callback(dataAddProductId) }, checkCartPromotion: function(product_id, cart_promotion, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : checkCartPromotion : products : product_id : ", product_id); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : checkCartPromotion : products : cart_promotion : ", cart_promotion); var check_promotion_status = false; var check_promotion_id = "0"; for (var i = 0; i < cart_promotion.length; i++) { if (cart_promotion[i].promotion_type_number != '6') { if (cart_promotion[i].promotion_data.promotion_row_display.buy.product.length) { for (var j = 0; j < cart_promotion[i].promotion_data.promotion_row_display.buy.product.length; j++) { if (cart_promotion[i].promotion_data.promotion_row_display.buy.product[j].product_id == product_id) { check_promotion_status = true; check_promotion_id = cart_promotion[i].promotion_id; } } } } } callback(check_promotion_status, check_promotion_id); }, removeCartPromotion: function(check_promotion_status, check_promotion_id, cart_id, callback) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : removeCartPromotion : check_promotion_status : ", check_promotion_status); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : removeCartPromotion : check_promotion_id : ", check_promotion_id); var remove_cart_promotion_status = false; if (check_promotion_status && check_promotion_id != "0") { $virtualCartTypeB.postCartPromotionDelete(check_promotion_id, cart_id, function(output) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : removeCartPromotion : postCartPromotionDelete : output : ", output); remove_cart_promotion_status = true; callback(remove_cart_promotion_status); }); } else { callback(remove_cart_promotion_status); } }, removeProduct: function(product_id, idx) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : removeProduct : ", " product_id : ", product_id); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : removeProduct : ", " idx : ", idx); $virtualCartTypeB.updateStatus([{ name: "loaderCartAddStatus", status: "show" }, { name: "bodyPromotionsAddStatus", status: "edit" }, { name: "bodyProductsAddStatus", status: "edit" }, { name: "bodyPricesAddStatus", status: "edit" }, { name: "bodyNoteAddStatus", status: "edit" }]); $virtualCartTypeB.getCart(function(currentCart) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : removeProduct : currentCart.cart_row_array.length : ", currentCart.cart_row_array.length); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : removeProduct : currentCart : ", currentCart); $virtualCartTypeB.products().checkCartPromotion(product_id, currentCart.cart_promotion, function(check_promotion_status, check_promotion_id) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : removeProduct : checkPromotion : check_promotion_status : ", check_promotion_status); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : removeProduct : checkPromotion : check_promotion_id : ", check_promotion_id); $virtualCartTypeB.products().removeCartPromotion(check_promotion_status, check_promotion_id, currentCart.cart_id, function(remove_cart_promotion_status) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : products : removeProduct : checkPromotion : removeCartPromotion : remove_cart_promotion_status : ", remove_cart_promotion_status); UiCart.delegate.product.updateAmount(product_id, 0); var time = setInterval(function() { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : removeProduct : product_id : ", product_id); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : removeProduct : !UiCart.delegate.product.isSelected : ", !UiCart.delegate.product.isSelected(product_id)); if (!UiCart.delegate.product.isSelected(product_id)) { window.clearInterval(time); $virtualCartTypeB.isLoad(); } }, 200); }); }); }); }, quantityProduct: function(product_id, idx, status) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : quantityProduct : ", " product_id : ", product_id); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : quantityProduct : ", " idx : ", idx); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : quantityProduct : ", " status : ", status); var product = $virtualCartTypeB.displayView().bodyProductsId(product_id, idx); var oldQtn = parseFloat(product.find('.qty').text()); var newQtn = oldQtn; if (status == 'add') { newQtn = newQtn + 1; } else if (status == 'minus') { newQtn = newQtn - 1; } $virtualCartTypeB.products().checkProduct(product_id, function(product_stock) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : quantityProduct : product_stock : ", product_stock); if (newQtn <= product_stock) { $virtualCartTypeB.updateStatus([{ name: "loaderCartAddStatus", status: "show" }, { name: "bodyPromotionsAddStatus", status: "edit" }, { name: "bodyProductsAddStatus", status: "edit" }, { name: "bodyPricesAddStatus", status: "edit" }, { name: "bodyNoteAddStatus", status: "edit" }]); UiCart.delegate.product.updateAmount(product_id, newQtn); var time = setInterval(function() { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : quantityProduct : product_id : ", product_id); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : quantityProduct : !UiCart.delegate.product.isProgress : ", !UiCart.delegate.product.isProgress(product_id)); if (!UiCart.delegate.product.isProgress(product_id)) { window.clearInterval(time); $virtualCartTypeB.isLoad(); } }, 200); } else if (product_stock == -1) { $virtualCartTypeB.updateStatus([{ name: "loaderCartAddStatus", status: "show" }, { name: "bodyPromotionsAddStatus", status: "edit" }, { name: "bodyProductsAddStatus", status: "edit" }, { name: "bodyPricesAddStatus", status: "edit" }, { name: "bodyNoteAddStatus", status: "edit" }]); UiCart.delegate.product.updateAmount(product_id, newQtn); var time = setInterval(function() { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : quantityProduct : product_id : ", product_id); $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB.products : products : quantityProduct : !UiCart.delegate.product.isProgress : ", !UiCart.delegate.product.isProgress(product_id)); if (!UiCart.delegate.product.isProgress(product_id)) { window.clearInterval(time); $virtualCartTypeB.isLoad(); } }, 200); } }); }, }; return products; }; /* quantity */ /* loadData */ $virtualCartTypeB.isLoad = function() { $virtualCartTypeB.updateStatus([{ name: "loaderCartAddStatus", status: "show" }, { name: "bodyPromotionsAddStatus", status: "edit" }, { name: "bodyProductsAddStatus", status: "edit" }, { name: "bodyPricesAddStatus", status: "edit" }, { name: "bodyNoteAddStatus", status: "edit" }]); $virtualCartTypeB.Refresh(); }; /* loadData */ /* checkout */ $virtualCartTypeB.checkout = function() { $virtualCartTypeB.getCart(function(currentCart) { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : checkout : currentCart : ", currentCart); return window.location.href = currentCart.cart_checkout_link; }); } $virtualCartTypeB.checkoutUrl = function() { $virtualCartTypeB.displayView().consoleLog("$virtualCartTypeB : checkoutUrl : $virtualCartTypeB.urlCheckout : ", $virtualCartTypeB.urlCheckout); return window.location.href = ($virtualCartTypeB.language == 'th') ? $virtualCartTypeB.urlCheckout + "&lang=th" :$virtualCartTypeB.urlCheckout; } /* checkout */ /* open */ $virtualCartTypeB.isCart = function() { if (!$virtualCartTypeB.displayView().cartContainerStatus("show")) { $virtualCartTypeB.isLoad(); $virtualCartTypeB.updateStatus([{ name: "cartContainerAddStatus", status: "show" }]); } else { $virtualCartTypeB.updateStatus([{ name: "cartContainerRemoveStatus", status: "show" }]); $virtualCartTypeB.displayView().bodyProductsReset(); } }; /* open */ /* shop */ $(function() { var shopId = parseFloat(CUR_THEME.shop_id()); switch (shopId) { /* support language ('en','th') */ /* case 'Demo': var language = 'en'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_basket01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = $virtualCartTypeB.icnPath + 'icnt_outline_basket01_light@2x.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; */ case 355: /* gettester */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_basket01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1118/0812/118812t1528466774.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 459: /* xspeed */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 467: /* xspeed */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 474: /* rmaphone */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 495: /* proplugin */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart03_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; /* case 523: var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); */ break case 544: /* sirikhun */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 598: /* krthai */ var language = 'en'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_basket01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 646: /* myhappyphone */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_basket01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 636: /* allbestk */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 676: /* flashmalls */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart02_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; /* case 699: worldcamera var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart03_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break */ case 713: /* gygy */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 717: /* hongmin */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_basket01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1118/0812/118812t1528466774.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 718: /* seselect */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 723: /* eindhoven */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart04_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 726: /* pet2home */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart03_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 728: /* savehouse */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_basket01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 732: /* tastyshabu */ var language = 'th'; var iconOpen = 'https://image.getappeasy.com/src/images/2000/1190/0594/190594t1533897780.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_light@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1190/0595/190595t1533897782.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 738: /* misamisa */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart03_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 740: /* memento */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_basket01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 743: /* smarthome */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart03_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break; case 747: /* uandv */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart03_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 753: /* evotech */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 754: /* infosat */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 765: /* supercheap */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 528: /* gaoyang */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 498: /* */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart02_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 701: /* */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 550: /* */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart02_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 731: /* iambeauty */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_fill_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 772: /* 21style */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 777: /* bypshop */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 783: /* maeju */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 786: /* geniusgadgets */ var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 787: /* gdemo001 */ var language = 'en'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break case 635: /* lightmax */ var language = 'en'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break /* case 792: vono var language = 'th'; var iconOpen = $virtualCartTypeB.icnPath + 'icnt_outline_cart01_dark@2x.png'; var iconClose = $virtualCartTypeB.icnPath + 'icnt_fill_close01_dark@2x.png'; var iconEmpty = 'https://image.getappeasy.com/src/images/2000/1139/0472/139472t1530250175.png'; $virtualCartTypeB.install(language, shopId, iconOpen, iconClose, iconEmpty); break */ default: break; } }); /* shop */ _ui_share_app.directive('componentYoutubeChannel', function ($rootScope, $routeParams) { var templateName = 'componentYoutubeChannel'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', youtubekey: '@youtubekey', channelid: '@channelid', maxresult: '@maxresult', loadmore: '@loadmore', delayrequest: '@delayrequest', name:'@name', texthead:'@texthead', data:'@data', loadbutton: '@loadbutton' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window, $http) { /** * build pagination by youtube return data * @params data (ObjectArray) * @return array */ $scope.dataArray = []; $scope.pagination_data_youtube = {}; $scope.buildYoutubePagination = function (data) { $scope.pagination_data_youtube = {}; var generateRangeArray = function (total_items, per_page, cur_page) { var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data_youtube = {}; $scope.pagination_data_youtube.cur_page = 1; $scope.pagination_data_youtube.per_page = parseInt(data.pageInfo.resultsPerPage); $scope.pagination_data_youtube.result_rows = parseInt(data.items.length); $scope.pagination_data_youtube.total_rows = parseInt(data.pageInfo.totalResults); $scope.pagination_data_youtube.max_page = Math.ceil($scope.pagination_data_youtube.total_rows / $scope.pagination_data_youtube.per_page); $scope.pagination_data_youtube.prev_page = (typeof data.prevPageToken !== 'undefined') ? data.prevPageToken : ""; $scope.pagination_data_youtube.next_page = (typeof data.nextPageToken !== 'undefined') ? data.nextPageToken : ""; $scope.pagination_data_youtube.page_array = generateRangeArray($scope.pagination_data_youtube.total_rows, $scope.pagination_data_youtube.per_page, $scope.pagination_data_youtube.cur_page); }; /** * get data from youtube channel * @params none * @return array */ $scope.pageToken = $routeParams.pageToken; $scope.isLoadMore = true; $scope.doubleRequest = true; $scope.getData = function (pageTokenString) { $scope.isLoadMore = true; var youtube_key = "AIzaSyAyGYMMkqOlqbBCS3XQrOepa9zuMxpaPqc"; var youtube_channel_id = $scope.channelid; var pageToken = (typeof $routeParams.pageToken == "undefined") ? "" : $routeParams.pageToken; var maxRequest = $scope.maxresult; if(typeof pageTokenString !== 'undefined' && pageTokenString !== ""){ pageToken = pageTokenString; } var dataSendYT = { "key": youtube_key, "channelId": youtube_channel_id, /*"UC5zymscW1RC6CVnXaGXPA6Q",*/ "part": "snippet", "order": "date", "maxResults": maxRequest, "pageToken": pageToken }; $http.get("https://www.googleapis.com/youtube/v3/search", {params: dataSendYT}).then(function (e) { console.log("getData: youtube api", dataSendYT, e); if (e.data.items.length) { if($scope.dataArray.length){ $scope.dataArray = $scope.dataArray.concat(e.data.items); } else{ $scope.dataArray = e.data.items; } $scope.isLoadMore = false; /*var fetchStatistics = false; if(fetchStatistics){ angular.forEach($scope.dataArray, function (i, k) { i.stat = {}; $http.get('https://www.googleapis.com/youtube/v3/videos', { params: { "key": key, "id": i.id.videoId, "part": "statistics" } }).then(function (res) { if (res.status == 200) { i.stat = res.data.items[0].statistics } }); }); }*/ $scope.buildYoutubePagination(e.data); if($scope.delayrequest == "1" && $scope.doubleRequest){ $scope.doubleRequest = false; $timeout(function(){ $scope.showMore(); },1000); } } }); }; /* Fetch data*/ $scope.getData(); /* Watch PageToken Params */ $scope.$watch('pageToken', function(newValue,oldValue){ if(!newValue || newValue == "" || typeof newValue === 'undefined'){ return; } /*$scope.getData(newValue);*/ }); /* Load More Items */ $scope.showMore = function(){ $scope.getData($scope.pagination_data_youtube.next_page); }; $scope.watchVideo = function(videoId){ if(!videoId || videoId === ""){ return; } var code = ''; angular.element('component-youtube-channel #videoYoutubePlayer').html(code); angular.element('component-youtube-channel ._component_video_sreen_block').addClass('active'); $timeout(function(){ angular.element('component-youtube-channel #videoYoutubePlayer iframe').addClass("active"); },300); }; $scope.closeVideo = function(){ angular.element('component-youtube-channel #videoYoutubePlayer iframe').removeClass("active"); $timeout(function(){ angular.element('component-youtube-channel #videoYoutubePlayer').html(""); angular.element('component-youtube-channel ._component_video_sreen_block').removeClass('active'); }, 700); }; }; return promise; }); /* Directive when child nodes loaded -> make parent add class */ _ui_share_app.directive("parentImageLazy", function () { return { restrict: "A", link: function (scope, element, attrs) { element.bind('load', function () { element.parent().addClass('image_loaded'); }); } }; }); _ui_share_app.directive('componentYoutubeChannelB', function ($rootScope, $routeParams) { var templateName = 'componentYoutubeChannelB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', youtubekey: '@youtubekey', channelid: '@channelid', maxresult: '@maxresult', loadmore: '@loadmore', delayrequest: '@delayrequest', name:'@name', texthead:'@texthead', data:'@data', loadbutton: '@loadbutton' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window, $http) { /** * build pagination by youtube return data * @params data (ObjectArray) * @return array */ $scope.dataArray = []; $scope.pagination_data_youtube = {}; $scope.buildYoutubePagination = function (data) { $scope.pagination_data_youtube = {}; var generateRangeArray = function (total_items, per_page, cur_page) { var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data_youtube = {}; $scope.pagination_data_youtube.cur_page = 1; $scope.pagination_data_youtube.per_page = parseInt(data.pageInfo.resultsPerPage); $scope.pagination_data_youtube.result_rows = parseInt(data.items.length); $scope.pagination_data_youtube.total_rows = parseInt(data.pageInfo.totalResults); $scope.pagination_data_youtube.max_page = Math.ceil($scope.pagination_data_youtube.total_rows / $scope.pagination_data_youtube.per_page); $scope.pagination_data_youtube.prev_page = (typeof data.prevPageToken !== 'undefined') ? data.prevPageToken : ""; $scope.pagination_data_youtube.next_page = (typeof data.nextPageToken !== 'undefined') ? data.nextPageToken : ""; $scope.pagination_data_youtube.page_array = generateRangeArray($scope.pagination_data_youtube.total_rows, $scope.pagination_data_youtube.per_page, $scope.pagination_data_youtube.cur_page); }; /** * get data from youtube channel * @params none * @return array */ $scope.pageToken = $routeParams.pageToken; $scope.isLoadMore = true; $scope.doubleRequest = true; $scope.getData = function (pageTokenString) { $scope.isLoadMore = true; var youtube_key = "AIzaSyAyGYMMkqOlqbBCS3XQrOepa9zuMxpaPqc"; var youtube_channel_id = $scope.channelid; var pageToken = (typeof $routeParams.pageToken == "undefined") ? "" : $routeParams.pageToken; var maxRequest = $scope.maxresult; if(typeof pageTokenString !== 'undefined' && pageTokenString !== ""){ pageToken = pageTokenString; } var dataSendYT = { "key": youtube_key, "channelId": youtube_channel_id, /*"UC5zymscW1RC6CVnXaGXPA6Q",*/ "part": "snippet", "order": "date", "maxResults": maxRequest, "pageToken": pageToken }; $http.get("https://www.googleapis.com/youtube/v3/search", {params: dataSendYT}).then(function (e) { console.log("getData: youtube api", dataSendYT, e); if (e.data.items.length) { if($scope.dataArray.length){ $scope.dataArray = $scope.dataArray.concat(e.data.items); } else{ $scope.dataArray = e.data.items; } $scope.isLoadMore = false; /*var fetchStatistics = false; if(fetchStatistics){ angular.forEach($scope.dataArray, function (i, k) { i.stat = {}; $http.get('https://www.googleapis.com/youtube/v3/videos', { params: { "key": key, "id": i.id.videoId, "part": "statistics" } }).then(function (res) { if (res.status == 200) { i.stat = res.data.items[0].statistics } }); }); }*/ $scope.buildYoutubePagination(e.data); if($scope.delayrequest == "1" && $scope.doubleRequest){ $scope.doubleRequest = false; $timeout(function(){ $scope.showMore(); },1000); } } }); }; /* Fetch data*/ $scope.getData(); /* Watch PageToken Params */ $scope.$watch('pageToken', function(newValue,oldValue){ if(!newValue || newValue == "" || typeof newValue === 'undefined'){ return; } /*$scope.getData(newValue);*/ }); /* Load More Items */ $scope.showMore = function(){ $scope.getData($scope.pagination_data_youtube.next_page); }; $scope.watchVideo = function(videoId){ if(!videoId || videoId === ""){ return; } var code = ''; angular.element('component-youtube-channel-b #videoYoutubePlayer').html(code); angular.element('component-youtube-channel-b ._component_video_sreen_block').addClass('active'); $timeout(function(){ angular.element('component-youtube-channel-b #videoYoutubePlayer iframe').addClass("active"); },300); }; $scope.closeVideo = function(){ angular.element('component-youtube-channel-b #videoYoutubePlayer iframe').removeClass("active"); $timeout(function(){ angular.element('component-youtube-channel-b #videoYoutubePlayer').html(""); angular.element('component-youtube-channel-b ._component_video_sreen_block').removeClass('active'); }, 700); }; }; return promise; }); /* Directive when child nodes loaded -> make parent add class */ _ui_share_app.directive("parentImageLazy", function () { return { restrict: "A", link: function (scope, element, attrs) { element.bind('load', function () { element.parent().addClass('image_loaded'); }); } }; }); _ui_share_app.directive('componentYoutubeChannelC', function ($rootScope, $routeParams) { var templateName = 'componentYoutubeChannelC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', youtubekey: '@youtubekey', channelid: '@channelid', maxresult: '@maxresult', loadmore: '@loadmore', delayrequest: '@delayrequest', name:'@name', texthead:'@texthead', data:'@data', loadbutton: '@loadbutton' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window, $http) { /** * build pagination by youtube return data * @params data (ObjectArray) * @return array */ $scope.dataArray = []; $scope.pagination_data_youtube = {}; $scope.buildYoutubePagination = function (data) { $scope.pagination_data_youtube = {}; var generateRangeArray = function (total_items, per_page, cur_page) { var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data_youtube = {}; $scope.pagination_data_youtube.cur_page = 1; $scope.pagination_data_youtube.per_page = parseInt(data.pageInfo.resultsPerPage); $scope.pagination_data_youtube.result_rows = parseInt(data.items.length); $scope.pagination_data_youtube.total_rows = parseInt(data.pageInfo.totalResults); $scope.pagination_data_youtube.max_page = Math.ceil($scope.pagination_data_youtube.total_rows / $scope.pagination_data_youtube.per_page); $scope.pagination_data_youtube.prev_page = (typeof data.prevPageToken !== 'undefined') ? data.prevPageToken : ""; $scope.pagination_data_youtube.next_page = (typeof data.nextPageToken !== 'undefined') ? data.nextPageToken : ""; $scope.pagination_data_youtube.page_array = generateRangeArray($scope.pagination_data_youtube.total_rows, $scope.pagination_data_youtube.per_page, $scope.pagination_data_youtube.cur_page); }; /** * get data from youtube channel * @params none * @return array */ $scope.pageToken = $routeParams.pageToken; $scope.isLoadMore = true; $scope.doubleRequest = true; $scope.getData = function (pageTokenString) { $scope.isLoadMore = true; var youtube_key = "AIzaSyAyGYMMkqOlqbBCS3XQrOepa9zuMxpaPqc"; var youtube_channel_id = $scope.channelid; var pageToken = (typeof $routeParams.pageToken == "undefined") ? "" : $routeParams.pageToken; var maxRequest = $scope.maxresult; if(typeof pageTokenString !== 'undefined' && pageTokenString !== ""){ pageToken = pageTokenString; } var dataSendYT = { "key": youtube_key, "channelId": youtube_channel_id, /*"UC5zymscW1RC6CVnXaGXPA6Q",*/ "part": "snippet", "order": "date", "maxResults": maxRequest, "pageToken": pageToken }; $http.get("https://www.googleapis.com/youtube/v3/search", {params: dataSendYT}).then(function (e) { console.log("getData: youtube api", dataSendYT, e); if (e.data.items.length) { if($scope.dataArray.length){ $scope.dataArray = $scope.dataArray.concat(e.data.items); } else{ $scope.dataArray = e.data.items; } $scope.isLoadMore = false; /*var fetchStatistics = false; if(fetchStatistics){ angular.forEach($scope.dataArray, function (i, k) { i.stat = {}; $http.get('https://www.googleapis.com/youtube/v3/videos', { params: { "key": key, "id": i.id.videoId, "part": "statistics" } }).then(function (res) { if (res.status == 200) { i.stat = res.data.items[0].statistics } }); }); }*/ $scope.buildYoutubePagination(e.data); if($scope.delayrequest == "1" && $scope.doubleRequest){ $scope.doubleRequest = false; $timeout(function(){ $scope.showMore(); },1000); } } }); }; /* Fetch data*/ $scope.getData(); /* Watch PageToken Params */ $scope.$watch('pageToken', function(newValue,oldValue){ if(!newValue || newValue == "" || typeof newValue === 'undefined'){ return; } /*$scope.getData(newValue);*/ }); /* Load More Items */ $scope.showMore = function(){ $scope.getData($scope.pagination_data_youtube.next_page); }; $scope.watchVideo = function(videoId){ if(!videoId || videoId === ""){ return; } var code = ''; angular.element('component-youtube-channel-b #videoYoutubePlayer').html(code); angular.element('component-youtube-channel-b ._component_video_sreen_block').addClass('active'); $timeout(function(){ angular.element('component-youtube-channel-b #videoYoutubePlayer iframe').addClass("active"); },300); }; $scope.closeVideo = function(){ angular.element('component-youtube-channel-b #videoYoutubePlayer iframe').removeClass("active"); $timeout(function(){ angular.element('component-youtube-channel-b #videoYoutubePlayer').html(""); angular.element('component-youtube-channel-b ._component_video_sreen_block').removeClass('active'); }, 700); }; }; return promise; }); /* Directive when child nodes loaded -> make parent add class */ _ui_share_app.directive("parentImageLazy", function () { return { restrict: "A", link: function (scope, element, attrs) { element.bind('load', function () { element.parent().addClass('image_loaded'); }); } }; }); _ui_share_app.directive('angularYoutube', function($sce) { return { restrict: 'E', scope: { video: '=' }, replace: true, template: '
', link: function(scope) { scope.$watch('video', function(newVal) { if (newVal) { scope.url = $sce.trustAsResourceUrl("http://www.youtube.com/embed/" + newVal); } }); } } }); _ui_share_app.directive('configColor', function ($rootScope, $routeParams) { var templateName = 'configColor'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { 'use':'@use', 'usesub':'@usesub', 'primary':'@primary', /* Primary Color */ 'secondary':'@secondary', /* Secondary Color */ 'special':'@special', /* Special (additional) Color */ 'specialtext':'@specialtext', /* Special (additional) Color */ 'placeholdercolor':'@placeholdercolor', 'placeholderprimary':'@placeholderprimary', 'placeholdersecondary':'@placeholdersecondary', 'bgprimary':'@bgprimary', 'bgsecondary':'@bgsecondary', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) {}; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.viewExample = false; $scope.showExample = function(){ if(!$scope.viewExample){ return $scope.viewExample = true; } return $scope.viewExample = false; }; /* hex to rgb * @param {hex} color code * @return color object {r,g,b} */ $scope.hexToRgb = function(hex) { var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function(m, r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16) } : null; }; /* lighten or darken color * @param {colorCode} original color code * @param {percent} use 0.2 for lighten 120% / use -0.20 for darken 120% * @return rgb color code */ $scope.LightenDarkenColor = function(hex, lum) { /*var usePound = false; if (col[0] == "#") { col = col.slice(1); usePound = true; } var num = parseInt(col,16); var r = (num >> 16) + amt; if (r > 255) r = 255; else if (r < 0) r = 0; var b = ((num >> 8) & 0x00FF) + amt; if (b > 255) b = 255; else if (b < 0) b = 0; var g = (num & 0x0000FF) + amt; if (g > 255) g = 255; else if (g < 0) g = 0; return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16); */ hex = String(hex).replace(/[^0-9a-f]/gi, ''); if (hex.length < 6) { hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]; } lum = lum || 0; var rgb = "#", c, i; for (i = 0; i < 3; i++) { c = parseInt(hex.substr(i*2,2), 16); c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16); rgb += ("00"+c).substr(c.length); } return rgb; }; $scope.ColorType = $scope.use; $scope.ColorSubType = $scope.usesub; $scope.ColorTypePrimary = $scope.primary; $scope.ColorTypeSecondary = $scope.secondary; $scope.ColorTypeSpecial = $scope.special; $scope.ColorTypePlaceholder = $scope.placeholdercolor; console.log("ColorType",$scope.ColorType); $scope.$watch('ColorType', function (newValue, oldValue) { if(!newValue) return; switch(newValue){ case 'primary.light': $scope.buildPrimaryLight($scope.ColorTypePrimary); break; case 'primary.dark': $scope.buildPrimaryDark($scope.ColorTypePrimary); break; } $scope.buildSpecialColor($scope.ColorTypeSpecial); }); $scope.$watch('ColorSubType', function (newValue, oldValue) { if(!newValue) return; switch(newValue){ case 'secondary.light': $scope.buildSecondaryLight($scope.ColorTypeSecondary); break; case 'secondary.dark': $scope.buildSecondaryDark($scope.ColorTypeSecondary); break; } }); /* Build Color By Type : Primary.Light */ $scope.buildPrimaryLight = function(mainColor){ $scope.colorMain = mainColor; $scope.colorDarker = $scope.LightenDarkenColor(mainColor, -0.15); $scope.colorDarkest = $scope.LightenDarkenColor(mainColor, -0.30); }; /* Build Color By Type : Primary.Dark */ $scope.buildPrimaryDark = function(mainColor){ $scope.colorMain = mainColor; $scope.colorDarker = $scope.LightenDarkenColor(mainColor, -0.15); $scope.colorDarkest = $scope.LightenDarkenColor(mainColor, -0.30); }; /* Build Color By Type : Secondary.Light */ $scope.buildSecondaryLight = function(mainColor){ $scope.colorSecondaryMain = mainColor; $scope.colorSecondaryDarker = $scope.LightenDarkenColor(mainColor, -0.15); $scope.colorSecondaryDarkest = $scope.LightenDarkenColor(mainColor, -0.30); }; /* Build Color By Type : Secondary.Dark */ $scope.buildSecondaryDark = function(mainColor){ $scope.colorSecondaryMain = mainColor; $scope.colorSecondaryDarker = $scope.LightenDarkenColor(mainColor, -0.15); $scope.colorSecondaryDarkest = $scope.LightenDarkenColor(mainColor, -0.30); }; /* Build Color By Type : Special */ $scope.buildSpecialColor = function(mainColor){ $scope.colorSpecialMain = mainColor; $scope.colorSpecialDarker = $scope.LightenDarkenColor(mainColor, -0.15); $scope.colorSpecialDarkest = $scope.LightenDarkenColor(mainColor, -0.30); }; /* Build Color By Type : Placeholdercolor.Light $scope.buildPlaceholderLight = function(mainColor){ $scope.colorMain = mainColor; $scope.colorDarker = $scope.LightenDarkenColor(mainColor, -0.15); $scope.colorDarkest = $scope.LightenDarkenColor(mainColor, -0.30); };/* /* Build Color By Type : Placeholdercolor.Dark $scope.buildPlaceholderDark = function(mainColor){ $scope.colorMain = mainColor; $scope.colorDarker = $scope.LightenDarkenColor(mainColor, -0.15); $scope.colorDarkest = $scope.LightenDarkenColor(mainColor, -0.30); }; */ /* Show Debug Button Only Localhost */ $scope.showDebug = function(){ return (window.location.host === 'localhost' || typeof $routeParams.debug !== 'undefined' || CUR_THEME.shop_id() == 395) ? true : false; }; }; return promise; }); _ui_share_app.directive('configFont', function ($rootScope, $routeParams) { var templateName = 'configFont'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', fontname: '@family', fontweight: '@weight', fontthai: '@thai', overide: '@overide', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function (scope, element, attr) { if(typeof attr.family !== 'undefined' && attr.family !== ''){ if(attr.family.indexOf(",")!==-1){ var fontArray = attr.family.split(","); if(attr.thai == "true" || attr.thai == "1"){ scope._font_link = "https://fonts.googleapis.com/css?family="+fontArray.join(":400,700|")+"&subset=thai"; } else { scope._font_link = "https://fonts.googleapis.com/css?family="+fontArray.join(":400,700|"); } scope._font_link.replace("+",","); } else { if(attr.thai == "true" || attr.thai == "1"){ scope._font_link = "https://fonts.googleapis.com/css?family="+attr.family+":400,700&subset=thai"; } else { scope._font_link = "https://fonts.googleapis.com/css?family="+attr.family+":400,700"; } scope._font_link.replace("+",","); } } }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._host = _ui_share_host + templateName + '/'; $scope._font_path = CUR_THEME.app_url() + "sitefiles/font_license/"; $scope._params = $routeParams; $scope._font_link = ''; $scope._font_family = $scope.fontname; $scope._use_google_fonts = true; $scope._use_license_fonts = false; /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 999999) + 100000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._check_overide = function(){ return true; /* force display font */ if($scope.overide != '' && $scope.overide != 0){ return true; } return false; }; /* check if this font in license font */ $scope.licenseCommercial = ["db_metta_x"]; /* always use lower cse for check */ $scope.validateLicense = function(n){ var fontName = n.toLowerCase().trim(); var pos = $scope.licenseCommercial.indexOf(fontName); if(pos !== -1){ return true; } return false; }; $scope.$watch('_font_family', function(newValue, oldValue){ if($scope.validateLicense(newValue)){ $scope._use_google_fonts = false; $scope._use_license_fonts = true; return; } }); $scope.loadLicenseFont = function(){ var fontName = $scope._font_family.toLowerCase().trim(); var fontArr = fontName.split(" "); var fontUrl = fontArr.join("_"); return $scope._font_path + fontArr + '/stylesheet.css'; }; $scope.checkValidFont = function(){ var a = $scope._font_link; if(a.indexOf('db_supermarket') !== -1 && a.indexOf('fonts.googleapis') !== -1){ return false; } return true; }; }; return promise; }); _ui_share_app.directive('contactCode', function($rootScope, $routeParams) { var templateName = 'contactCode'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', code: '@code', contact: '@contact', button: '@button', background: '@background', primary: '@primary', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'google_map_frame': '?googleMapFrame', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { alert("กรุณากรอกอีเมลของท่านให้ถูกต้อง"); } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.name); formData.append('input_owner_contact', $scope.contact); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; }; return promise; });_ui_share_app.directive('contactCodeA', function($rootScope, $routeParams) { var templateName = 'contactCodeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', code: '@code', contact: '@contact', button: '@button', background: '@background', primary: '@primary', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'google_map_frame': '?googleMapFrame', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { alert("กรุณากรอกอีเมลของท่านให้ถูกต้อง"); } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.name); formData.append('input_owner_contact', $scope.contact); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; }; return promise; });_ui_share_app.directive('contactPageTypeA', function($rootScope, $routeParams) { var templateName = 'contactPageTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', contact: '@contact', background: '@background', primary: '@primary', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'form_company_name': '?formCompanyName', 'form_tel': '?formTel', 'form_address': '?formAddress', 'form_map_iframe': '?formMapIframe', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.shopCurrent = []; $scope.getShopCurrent = function() { GAEAPI.get('shop/current', [], $scope).then(function(e) { if (e.ok === 1) { $scope.shopCurrent = e.data; $scope.getsubAddress($scope.shopCurrent.shop_extend_data.address); $scope.getsubPhone($scope.shopCurrent.shop_extend_data.phone); $scope.getsubEmail($scope.shopCurrent.shop_extend_data.mail); } console.log("shopCurrent", $scope.shopCurrent); }); }; $scope.getShopCurrent(); $scope.getsubAddress = function(Address) { $scope.address_page = Address; console.log('address_page', $scope.address_page); if ($scope.address_page !== '' && typeof $scope.address_page !== 'undefined') { $scope.address_page_split = $scope.address_page.split("_"); console.log('address_page_split', $scope.address_page_split); $scope.address1_page = ''; $scope.address2_page = ''; if ($scope.address_page_split.length > 0) { $scope.address1_page = $scope.address_page_split[0]; } if ($scope.address_page_split.length > 1) { $scope.address2_page = $scope.address_page_split[1]; } } } $scope.getsubPhone = function(Phone) { $scope.phone_page = Phone; console.log('phone_page', $scope.phone_page); if ($scope.phone_page !== '' && typeof $scope.phone_page !== 'undefined') { $scope.phone_page_split = $scope.phone_page.split(","); console.log('phone_page_split', $scope.phone_page_split); $scope.phone1_page = ''; $scope.phone2_page = ''; if ($scope.phone_page_split.length > 0) { $scope.phone1_page_sub = $scope.phone_page_split[0].substring(1); $scope.phone1_page = $scope.phone_page_split[0]; } if ($scope.phone_page_split.length > 1) { $scope.phone2_page_sub = $scope.phone_page_split[1].substring(1); $scope.phone2_page = $scope.phone_page_split[1]; } } } $scope.getsubEmail = function(Email) { $scope.mail_page = Email; console.log('mail_page', $scope.mail_page); if ($scope.mail_page !== '' && typeof $scope.mail_page !== 'undefined') { $scope.mail_page_split = $scope.mail_page.split(","); console.log('mail_page_split', $scope.mail_page_split); $scope.mail1_page = ''; $scope.mail2_page = ''; if ($scope.mail_page_split.length > 0) { $scope.mail1_page_sub = $scope.mail_page_split[0].substring(1); $scope.mail1_page = $scope.mail_page_split[0]; } if ($scope.mail_page_split.length > 1) { $scope.mail2_page_sub = $scope.mail_page_split[1].substring(1); $scope.mail2_page = $scope.mail_page_split[1]; } } } /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; /* Watch Value */ $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { alert("กรุณากรอกอีเมลของท่านให้ถูกต้อง"); } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.name); formData.append('input_owner_contact', $scope.contact); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; if (data == 1) { /* window.location.href = 'job-done'; alert('ส่งข้อมูลเรียบร้อยแล้ว');*/ console.log("send_email", data); } else { /*alert("error");*/ console.log("send_email", data); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; }; return promise; });_ui_share_app.directive('contactPageTypeB', function($rootScope, $routeParams) { var templateName = 'contactPageTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', contact: '@contact', background: '@background', primary: '@primary', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_first_link': '?textFirstLink', 'branch_name_first': 'branchNameFirst', 'branch_address_first': 'branchAddressFirst', 'branch_code_map_first': 'branchCodeMapFirst', 'branch_email_first': 'branchEmailFirst', 'branch_name_second': 'branchNameSecond', 'branch_address_second': 'branchAddressSecond', 'branch_code_map_second': 'branchCodeMapSecond', 'branch_email_second': 'branchEmailSecond', }; promise.controller = function($scope, $timeout, $interval, $q, $window) { /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; /* Watch Value */ $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event) { var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if ($scope.isEmail($('#contact_form input[name="input_email"]').val())) { isPass = true; } else { alert("กรุณากรอกอีเมลของท่านให้ถูกต้อง"); } if (!($scope.isEmail($('#contact_form input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } if ($scope.name !== "" && $scope.contact !== "" && submit && isPass) { angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name', $scope.name); formData.append('input_owner_contact', $scope.contact); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; if (data == 1) { alert('ส่งข้อมูลเรียบร้อยแล้ว'); } else { alert("error"); } }, error: function(jqXHR, textStatus, errorThrown) { setTimeout(function() { angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); }, 2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; }; return promise; });_ui_share_app.directive('contactPageTypeC', function($rootScope, $routeParams) { var templateName = 'contactPageTypeC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', contact: '@contact', background: '@background', primary: '@primary', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'text_first': '?textFirst', 'text_first_link': '?textFirstLink', 'text_title': '?textTitle', 'img_contact': '?imgContact', 'description_contact': '?descriptionContact', 'img_map': '?imgMap', 'google_map_frame': '?googleMapFrame' }; promise.controller = function($scope, $timeout, $interval, $q, $window) { /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_message_valid = false; /* Watch Value */ $scope.$watch('input_email', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_email_valid = false; return; } if ($scope.isEmail(newValue)) { $scope.input_email_valid = true; } else { $scope.input_email_valid = false; } }); $scope.$watch('input_name', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_message', function(newValue, oldValue) { if (!newValue || newValue === "") { $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); $scope.complain = function($event) { var submit = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); $(this).closest('.form_block_control').find('.round').addClass('error'); $(this).closest('.form_block_control .select').find('.after').addClass('error'); } else { $(this).closest('.form-group').find('span').removeClass('error'); } }); $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $('html,body').animate({ scrollTop: $(this).offset().top - 160 }, 'slow'); submit = false; return false; } }); var isPass = false; if ($scope.isEmail($('#complainForm input[name="input_email"]').val())) { isPass = true; } if (!($scope.isEmail($('#complainForm input[name="input_email"]').val()))) { $("[name='input_email']").addClass('error'); } else { $("[name='input_email']").removeClass('error'); } var formData = new FormData($($event.currentTarget).closest('form')[0]); if (CUR_THEME.shop_id() == 552) { formData.append('input_owner_name', 'duckypackprint'); formData.append('input_owner_contact', 'dkpackprint@gmail.com,web.getappeasy@gmail.com'); } else { return; } if (submit && isPass) { $.ajax({ url: _ui_share_host + '../sendgrid/send-email.php', method: 'POST', data: formData, dataType: "json", cache: false, contentType: false, processData: false, success: function(data, textStatus, jqXHR) { console.log('data:dfjdkfdjd', data); if (data == 1) { alert('ส่งข้อมูลเรียบร้อยแล้ว'); } else { alert("error"); } }, error: function(jqXHR, textStatus, errorThrown) { console.log('textStatus: ', textStatus); console.log('jqXHR: ', jqXHR); console.log('ERRORS: ' + errorThrown); alert("กรุณาลองใหม่อีกครั้ง"); return; } }); } else { alert("ตรวจสอบอีเมลให้ถูกต้อง"); } }; /* Valid Email */ $scope.isEmail = function(inputString) { var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; $('.map_frame').click(function() { $(this).find('iframe').addClass('clicked') }).mouseleave(function() { $(this).find('iframe').removeClass('clicked') }); }; return promise; });_ui_share_app.directive('productBadgeListsA', function($rootScope, $routeParams, $location) { var templateName = 'productBadgeListsA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewType = 'grid'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.productListSort = $scope._viewRouteParams().sort || "product_lifetime_start_asc"; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('badge-lists') !== -1) ? '/badge-lists' : '/badge-lists'; if (typeof $location.search().badge != 'undefined' && $location.search().badge != "") { otherParams += "?badge=" + $location.search().badge; paramsObj.badge = $location.search().badge; } // if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { // otherParams += "&referral_id=" + $location.search().referral_id; // paramsObj.referral_id = $location.search().referral_id; // } // if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { // otherParams += "&root_id=" + $location.search().root_id; // paramsObj.root_id = $location.search().root_id; // } // if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { // otherParams += "&referral_type=" + 'category'; // paramsObj.referral_type = 'category'; // } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $location.path(pathStr).search(paramsObj); }, 300); }; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); if($scope._viewRouteParams().badge != undefined){ var txt_filter_json = { 'badge_id_array': [18,$scope._viewRouteParams().badge], }; }else{ var txt_filter_json = { 'badge_id_array': [18], }; } var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': $scope.productListSort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); }; return promise; });_ui_share_app.directive('productBadgeListsB', function($rootScope, $routeParams, $location) { var templateName = 'productBadgeListsB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewType = 'grid'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.productListSort = $scope._viewRouteParams().sort || "product_lifetime_start_asc"; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('badge-lists') !== -1) ? '/badge-lists' : '/badge-lists'; if (typeof $location.search().badge != 'undefined' && $location.search().badge != "") { otherParams += "?badge=" + $location.search().badge; paramsObj.badge = $location.search().badge; } // if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { // otherParams += "&referral_id=" + $location.search().referral_id; // paramsObj.referral_id = $location.search().referral_id; // } // if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { // otherParams += "&root_id=" + $location.search().root_id; // paramsObj.root_id = $location.search().root_id; // } // if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { // otherParams += "&referral_type=" + 'category'; // paramsObj.referral_type = 'category'; // } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $location.path(pathStr).search(paramsObj); }, 300); }; $scope._viewRouteParams = function() { return $routeParams; }; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); if ($scope._viewRouteParams().badge != undefined) { var txt_filter_json = { 'badge_id_array': [18, $scope._viewRouteParams().badge], }; } else { var txt_filter_json = { 'badge_id_array': [18], }; } var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': $scope.productListSort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); }; return promise; }); _ui_share_app.directive('productCardTypeA', function ($rootScope, $routeParams) { var templateName = 'productCardTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', badgeid: '@badgeid', imgpath: '@imgpath', img: '@img', text: '@text', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ console.log("badgeid",$scope.badgeid); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'product_oldest_create'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; if($scope.badgeid != null || $scope.badgeid != ""){ option.badge_id_array=[18,$scope.badgeid]; }else{ option.badge_id_array=[18]; } var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); /*$('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} });*/ }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; }; return promise; }); _ui_share_app.directive('productCardTypeAa', function ($rootScope, $routeParams) { var componentMain = 'productCardTypeA'; var componentChild = 'a'; var templatePathUrl = _ui_share_host + componentMain + '/expansions/' + componentChild + '/' + componentChild+ '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', badgeid: '@badgeid', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ console.log("badgeid",$scope.badgeid); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'product_oldest_create'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; if($scope.badgeid != null || $scope.badgeid != ""){ option.badge_id_array=[18,$scope.badgeid]; }else{ option.badge_id_array=[18]; } var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); /*$('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} });*/ }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; }; return promise; }); _ui_share_app.directive('productCardTypeB', function ($rootScope, $routeParams) { var templateName = 'productCardTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', coloractive: '@coloractive', textheader: '@textheader', textbuy: '@textbuy', btnstyle: '@btnstyle', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.ArrivalList = []; $scope.getArrivalList = function() { var txt_filter_json = { 'badge_id_array': [72] } var dataSend = { 'cur_page': 1, 'per_page': 8 }; GAEAPI.get('product/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.ArrivalList = res.data.dataList; } console.log("ArrivalList",$scope.ArrivalList); }); }; $scope.getArrivalList(); }; return promise; }); _ui_share_app.directive('productCardTypeC', function ($rootScope, $routeParams) { var templateName = 'productCardTypeC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', badgeid: '@badgeid', imgpath: '@imgpath', img: '@img', text: '@text', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ console.log("badgeid",$scope.badgeid); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'product_oldest_create'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; if($scope.badgeid != null || $scope.badgeid != ""){ option.badge_id_array=[18,$scope.badgeid]; }else{ option.badge_id_array=[18]; } var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); /*$('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} });*/ }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; }; return promise; }); _ui_share_app.directive('productDetailDealA', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailDealA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.forbidden = false; $scope._config = []; $scope._host = _ui_host + templateName + '/'; $scope.qtyProduct = 1; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; /* JQ: Scroll event */ angular.element($window).bind('scroll', function() { if (!$scope.data) { return; } var curPos = ($(document).scrollTop()); var properHeight = ($('.img_cover').height() * ($('.img_cover').length - 1)); console.debug("Cur pos", curPos, properHeight); if (curPos > properHeight) { angular.element('.block-background .bottom-info').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { angular.element('.block-background .bottom-info').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }); /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; /* deal data */ $scope.all_data = ""; $scope.data_tag = []; $scope.getData = function() { $scope.all_data = ""; var d = { 'txt_product_id': $scope._getPostIdFromURL(), }; GAEAPI.get('deal/id', d, $scope).then(function(e) { if (e.ok == 1) { $scope.all_data = e.data; $scope.data_tag = (e.data.product_set_array[0].product_tags).split(","); $scope.timeCountStart2($scope.all_data); console.log("dealsLists", $scope.all_data,$scope.data_tag); } }); }; $scope.getData(); /* end deal data */ /* Slider Send */ $scope.data = false; $scope.dataPreserve = false; /* Get product id from url or from component */ $scope._getPostIdFromURL = function() { var test = $scope.id; var a = $scope.id; if (typeof $routeParams.product_id !== 'undefined') { test = parseInt($routeParams.product_id); a = $routeParams.product_id; } if (typeof test === 'number' && test > 0) { return test; } else { var b = a.split("-"); return b[0]; } }; /* Get data by product id */ $scope.product_data_array = function() { GAEAPI.get('product/id', { 'txt_product_id': $scope._getPostIdFromURL() }).then(function(e) { if (e.ok == 1) { $scope.data = e.data; $scope.dataPreserve = e.data; $scope.buildVariantOption(e.data); $scope.buildDataProductRelate($scope._getPostIdFromURL()); } }); }; $scope.product_data_array(); $scope.dataRelate = []; $scope.buildDataProductRelate = function(product_id) { var j = { 'relate_product_id_array': [product_id], 'badge_id_array': [18] }; var d = { 'cur_page': 1, 'per_page': 6, 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('product/lists', d).then(function(e) { if (e.ok == 1) { $scope.dataRelate = e.data.dataList; console.log("dataRelate", $scope.dataRelate); } }); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope.data.product_id = dataVariants[i].product_id; $scope.data.product_sku = dataVariants[i].sku; $scope.data.product_price = dataVariants[i].price; $scope.data.product_compare_price = dataVariants[i].compare_price; break; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $timeout.cancel(s); $('select.variantSelector').each(function(idx, obj) { var optionElementFirst = $(this).find('option[data-index="' + idx + '"]').eq(0); optionElementFirst.prop("selected", true); $scope.onSelectVariantItems(optionElementFirst.attr('data-index'), optionElementFirst.attr('data-option')); }); }, 2000); }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope._makeProductToCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._makeProductToCarousel(); }, 500); } }); $scope.qty_original = 1; $scope.qty_current = 1; /* Click SLick Item */ $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; /* Calcu Nav Arrows */ $scope.maxHeight = 0; $scope.navArrowsCalculate = function() { var size = ($('img.img_gallery').eq(0).height() / 2); $scope.maxHeight = (size + 18); $('img.img_gallery').each(function() { if ($(this).height() > $scope.maxHeight) { $scope.maxHeight = $(this).height(); } }); return '-' + $scope.maxHeight + 'px'; }; $scope.navArrowWidth = function() { return $('#gallery_display').width() + 'px'; }; /* timeCount */ $scope.momentJs = { getDayString: function(timestamp) { return GAEAPI.time.dateFormat("D", timestamp); }, getMonthString: function(timestamp) { return GAEAPI.time.dateFormat("MMM", timestamp); }, getHoursString: function(timestamp) { return GAEAPI.time.dateFormat("hh", timestamp); }, getMinutesString: function(timestamp) { return GAEAPI.time.dateFormat("mm", timestamp); }, getSecondsString: function(timestamp) { return GAEAPI.time.dateFormat("ss", timestamp); }, getTimesString: function(timestamp) { return GAEAPI.time.dateFormat("hh : mm : ss", timestamp); } }; $scope.counter = 345600; $scope.timeDay = function() { var day = $scope.momentJs.getDayString($scope.counter); return day; } $scope.timeHours = function() { var hours = $scope.momentJs.getHoursString($scope.counter); return hours; } $scope.timeMinutes = function() { var minutes = $scope.momentJs.getMinutesString($scope.counter); return minutes; } $scope.timeSeconds = function() { var seconds = $scope.momentJs.getSecondsString($scope.counter); return seconds; } $scope.timeCount = function() { var time = $scope.momentJs.getTimesString($scope.counter); return time; } $scope.timeout_promise = null; $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.counter--; $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.viewType = 'description'; var selector = '.nav li'; $(selector).on('click', function() { $(selector).removeClass('active'); $(this).addClass('active'); }); $scope.toTop = function() { return window.scrollTo(0, 0); }; $scope.showPart = ""; $scope.countDown = function(settime) { var time_year = ""; var time_mount = ""; var time_date = ""; var time_hr = ""; var time_mi = ""; var time_se = ""; var timeA = ""; var timeB = ""; var timeC = ""; var timeDifference = ""; var timeDifference_temp = ""; var wan = ""; var l_wan = ""; var hour = ""; var l_hour = ""; var minute = ""; var second = ""; time_year = GAEAPI.time.dateFormat("YYYY", settime.product_lifetime.lifetime_end_time); time_mount = GAEAPI.time.dateFormat("M", settime.product_lifetime.lifetime_end_time); time_date = GAEAPI.time.dateFormat("D", settime.product_lifetime.lifetime_end_time); time_hr = GAEAPI.time.dateFormat("H", settime.product_lifetime.lifetime_end_time); time_mi = GAEAPI.time.dateFormat("m", settime.product_lifetime.lifetime_end_time); time_se = GAEAPI.time.dateFormat("s", settime.product_lifetime.lifetime_end_time); timeA = new Date(); /* วันเวลาปัจจุบัน */ timeB = new Date(time_year, (time_mount - 1), time_date, time_hr, time_mi, time_se, '0'); timeDifference = timeB.getTime() - timeA.getTime(); console.log("timeDifference", timeDifference); if (timeDifference >= 0) { timeDifference = timeDifference / 1000; timeDifference = Math.floor(timeDifference); wan = Math.floor(timeDifference / 86400); l_wan = timeDifference % 86400; hour = Math.floor(l_wan / 3600); l_hour = l_wan % 3600; minute = Math.floor(l_hour / 60); second = l_hour % 60; $scope.showPart = wan + " วัน " + pad(hour, 2) + " ชั่วโมง " + pad(minute, 2) + " นาที " + pad(second, 2) + " วินาที"; if (wan == 0 && hour == 0 && minute == 0 && second == 0) {} console.log("check_array", $scope.showPart); } }; $scope.timeout_promise2 = null; $scope.timeCountStart2 = function(settime) { $scope.timeout_promise2 = $timeout(function() { $scope.countDown(settime); $scope.timeCountStart2(settime); }, 1000); }; function pad(str, max) { str = str.toString(); return str.length < max ? pad("0" + str, max) : str; }; /*$scope.myFunction = function() { document.getElementById("myDropdown").classList.toggle("show"); } $scope.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } }*/ $scope._page_lists = false; $scope._page_lists_load = false; $scope._get_page_lists = function() { $scope._clear_page_lists(); var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'page_lastest_create' }; GAEAPI.get('page/lists', dataSend).then(function(res) { $scope._page_lists_load = true; if (res.ok === 1) { $scope._page_lists = res.data.dataList; angular.forEach($scope._page_lists, function(item, key) { if (item.page_search_url == "") { item.page_search_url = item.page_id; } }); } }); }; $scope._clear_page_lists = function() { $scope._page_lists = false; $scope._page_lists_load = false; }; $scope._get_page_lists(); $scope._page_category = false; $scope._page_category_load = false; $scope._get_page_category = function() { $scope._clear_page_lists(); var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_name_a-z' }; GAEAPI.get('referral/map', dataSend).then(function(res) { $scope._page_category_load = true; if (res.ok === 1) { $scope._page_category = res.data; } }); }; $scope._clear_page_category = function() { $scope._page_category = false; $scope._page_category_load = false; }; $scope._get_page_category(); $scope._testdata = [{ id: '1', Buy: '1', Price: '699', Discount: '0%' }, { id: '2', Buy: '3', Price: '550', Discount: '10%' }, { id: '3', Buy: '6', Price: '530', Discount: '15%' }, { id: '4', Buy: '12', Price: '520', Discount: '16%' }, { id: '5', Buy: '50', Price: '510', Discount: '17%' }]; $scope._get_page_category(); $scope.mkCarouselData = function(elem) { console.debug('mkCarouselData: trigger'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 5, slidesToScroll: 1, infinite: true, speed: 600, prevArrow: '', nextArrow: '', responsive: [{ breakpoint: 1330, settings: { slidesToShow: 5, } }, { breakpoint: 991, settings: { slidesToShow: 5, } }, { breakpoint: 767, settings: { slidesToShow: 5, } }, { breakpoint: 692, settings: { slidesToShow: 6, } }, { breakpoint: 540, settings: { slidesToShow: 3, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope._indata = $scope._testdata[0].id; $scope._indataPrice = $scope._testdata[0].Price; $scope._inputdata = function(data, Price) { $scope._indata = data; $scope._indataPrice = Price; }; }; return promise; });_ui_share_app.directive('productDetailDealB', function($rootScope, $routeParams, sliderProvider) { var templateName = 'productDetailDealB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { name: '@name', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataTag = false; $scope._dataArray = []; $scope.product_sku = ""; $scope.product_code = ""; $scope.product_price = 0; $scope.product_compare_price = 0; $scope._dataArrayState = { load: true, done: false }; $scope._getDataArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id, }; console.log('dataSend_Product', dataSend); GAEAPI.get('deal/id', dataSend).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data.product_set_array[0]; $scope.timeCountStart2(res.data); console.log("_getDataArray _dataArray : ", $scope._dataArray); $scope.dataPreserve = $scope._dataArray; if ($scope._dataArray.product_sku != undefined) { $scope.product_sku = $scope._dataArray.product_sku; } if ($scope._dataArray.product_code != undefined) { $scope.product_code = $scope._dataArray.product_code; } $scope.product_price = $scope.calculate($scope._dataArray.product_price, $scope._dataArray.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull($scope._dataArray.product_price, $scope._dataArray.product_compare_price, res.data.product_discount.discount_id, res.data.product_discount.discount_price, res.data.product_discount.discount_percent); if ($scope._dataArray.product_referral_display.category != 'undefined' && $scope._dataArray.product_referral_display.category != null) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } $scope.dataTag = $scope._dataArray.product_tags.split(","); $scope.qtyCurrentSize($scope._dataArray.product_total_variant, $scope._dataArray.product_total_stock); // $scope.buildVariantOption($scope._dataArray); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.showPart = ""; $scope.countDown = function(settime) { var time_year = ""; var time_mount = ""; var time_date = ""; var time_hr = ""; var time_mi = ""; var time_se = ""; var timeA = ""; var timeB = ""; var timeC = ""; var timeDifference = ""; var timeDifference_temp = ""; var wan = ""; var l_wan = ""; var hour = ""; var l_hour = ""; var minute = ""; var second = ""; time_year = GAEAPI.time.dateFormat("YYYY", settime.product_lifetime.lifetime_end_time); time_mount = GAEAPI.time.dateFormat("M", settime.product_lifetime.lifetime_end_time); time_date = GAEAPI.time.dateFormat("D", settime.product_lifetime.lifetime_end_time); time_hr = GAEAPI.time.dateFormat("H", settime.product_lifetime.lifetime_end_time); time_mi = GAEAPI.time.dateFormat("m", settime.product_lifetime.lifetime_end_time); time_se = GAEAPI.time.dateFormat("s", settime.product_lifetime.lifetime_end_time); timeA = new Date(); /* วันเวลาปัจจุบัน */ timeB = new Date(time_year, (time_mount - 1), time_date, time_hr, time_mi, time_se, '0'); timeDifference = timeB.getTime() - timeA.getTime(); console.log("timeDifference", timeDifference); if (timeDifference >= 0) { timeDifference = timeDifference / 1000; timeDifference = Math.floor(timeDifference); wan = Math.floor(timeDifference / 86400); l_wan = timeDifference % 86400; hour = Math.floor(l_wan / 3600); l_hour = l_wan % 3600; minute = Math.floor(l_hour / 60); second = l_hour % 60; $scope.showPart = wan + " วัน " + pad(hour, 2) + " ชั่วโมง " + pad(minute, 2) + " นาที " + pad(second, 2) + " วินาที"; if (wan == 0 && hour == 0 && minute == 0 && second == 0) {} console.log("check_array", $scope.showPart); } }; function pad(str, max) { str = str.toString(); return str.length < max ? pad("0" + str, max) : str; }; $scope.timeout_promise2 = null; $scope.timeCountStart2 = function(settime) { $scope.timeout_promise2 = $timeout(function() { $scope.countDown(settime); $scope.timeCountStart2(settime); }, 1000); }; $scope.mkCarousel = function(elem) { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 991, settings: { slidesToShow: 1, } }, { breakpoint: 767, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var dataSend = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.dataRelation = res.data; } }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getIdUrl = function() { var getData = []; var returnData = ''; if (typeof $routeParams.product_id !== 'undefined') { getData = $routeParams.product_id; returnData = getData.split("-"); return returnData[0]; } }; $scope.viewImg = 0; $scope.changeImg = function(i) { return $scope.viewImg = i; }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleStatres.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleStatres.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { if (price != undefined && price != 0) { pricefull = price; $scope._pricefullState.pricefull = 'not zero'; } else { pricefull = 0; $scope._pricefullState.pricefull = 'zero'; } } else { if (compare_price > 0 && compare_price != undefined) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope._calculateState = { calculate: 0 }; $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } if (calculate != undefined && calculate != 0) { $scope._calculateState.calculate = 'not zero'; } else { $scope._calculateState.calculate = 'zero'; } return (calculate > 0) ? calculate : 0; } $scope.qtyCurrentSize = function(product_total_variant, product_total_stock) { $scope.qty_current_size = []; console.log("qtyCurrentSize : product_total_variant : ", product_total_variant, "product_total_stock : ", product_total_stock); if (product_total_variant == 0) { if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < parseInt(product_total_stock); i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock < 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < 20; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock == 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else { $scope.qty_current_size_state = false; $scope.buy_state = false; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } } else if (product_total_variant > 0) { if (product_total_stock <= 0) { $scope.qty_current_size_state = false; $scope.buy_state = true; for (var i = 0; i < 1; i++) { $scope.qty_current_size.push(i + 1); } } else if (product_total_stock > 0) { $scope.qty_current_size_state = true; $scope.buy_state = true; for (var i = 0; i < product_total_stock; i++) { $scope.qty_current_size.push(i + 1); } } } $scope.qtyShow($scope.qty_current_size); }; $scope.htmlSelectTime = 0; $scope.qtyShow = function(array) { $scope.htmlSelectTime = 0; console.log("qtyShow ", array); var htmlOPT = ""; for (var i = 0; i < array.length; i++) { htmlOPT += ''; } console.log("qty_current_size htmlOPT", htmlOPT); if (htmlOPT != "") { $scope.htmlSelectTime = $timeout(function() { $('#qtyselect').html(htmlOPT); $timeout.cancel($scope.htmlSelectTime); }, 500); } } $scope.viewQuantity = function() { var check_int = 1; if ($(".d_qty").val() == undefined) { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); check_int = 1; } else if ($(".d_qty").val() == "? number:1 ?") { $(".d_qty").val("1"); check_int = parseInt($(".d_qty").val()); } else { check_int = parseInt($(".d_qty").val()); $(".d_qty").val(check_int); } return check_int; }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; $scope.makeVariantsClick(); }; $scope.dataVariantsPick = []; $scope.onSelectVariantItems = function($index, option_id) { console.log("onSelectVariantItems option_id:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; console.log("onSelectVariantItems dataVariantsPick:", $scope.dataVariantsPick); if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.findVariantsData($scope.dataVariantsPick); } }; $scope.findVariantsData = function(variantsPick) { function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); console.log("dataVariants :", dataVariants); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; if (dataVariants[i].sku != "") { $scope.product_sku = dataVariants[i].sku; } else { $scope.product_sku = $scope._dataArray.product_sku; } if (dataVariants[i].sku != "") { $scope.product_code = dataVariants[i].barcode; } else { $scope.product_code = $scope._dataArray.product_code; } $scope.product_price = $scope.calculate(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.product_compare_price = $scope.pricefull(dataVariants[i].price, dataVariants[i].compare_price, $scope._dataArray.product_discount.discount_id, $scope._dataArray.product_discount.discount_price, $scope._dataArray.product_discount.discount_percent); $scope.qtyCurrentSize(dataVariants.length, dataVariants[i].total_stock); break; } else { $scope.qty_current_size_state = false; $scope.buy_state = false; $scope.product_price = $scope._dataArray.product_price; $scope.product_compare_price = $scope._dataArray.product_compare_price; $scope.product_sku = $scope._dataArray.product_sku; $scope.product_code = $scope._dataArray.product_code; } } }; $scope.makeVariantsClick = function() { var s = $timeout(function() { $scope.buy_state = false; }, 100); }; $scope.viewInfo = 1; $scope.view = function(input) { $scope.viewInfo = input; } $scope._getDataArray($scope._getIdUrl()); }; return promise; });_ui_share_app.directive('productDetailDealF', function($rootScope, $routeParams, sliderProvider, $componentProductDetail) { var templateName = 'productDetailDealF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'E'; promise.scope = { imgpath: '@imgpath', promotelink: '@promotelink', id: '@id', }; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.link = function(scope, element, attr) {}; promise.controller = function($scope, $timeout, $interval, $window, $http, $location) { $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._idUrl = function(instr) { var outstr = instr.split("-", 1).join(""); return outstr; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.dataRelatetag = []; $scope.dataRelatetagState = { load: true, done: false }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.productRelateTag = function(product_tag) { $scope.dataRelatetagState = $scope.StateData(true, false); if (product_tag != '') { var tag = { 'tags': product_tag }; var dataSend = { 'cur_page': 1, 'per_page': 4, 'txt_filter_json': JSON.stringify(tag) }; } else { $scope.dataRelatetagState = $scope.StateData(false, true); $scope.dataRelatetag = []; return; } console.log("dataSend :", dataSend); GAEAPI.get('product/lists', dataSend).then(function(output) { $scope._dataArrayState = $scope.StateData(true, false); if (output.ok == 1) { // for (var i = 0; i < output.data.dataList.length; i++) { // if(output.data.dataList){ // $scope.dataRelatetag = output.data.dataList; // } // } $scope.dataRelatetag = output.data.dataList; console.log("dataSend :", output.data); } $scope._dataArrayState = $scope.StateData(false, true); // $scope.dataRelatetagState = $scope.StateData(false, true); }); }; $scope.all_data = ""; $scope.getData = function() { $scope.all_data = ""; var d = { 'txt_product_id': $scope._idUrl($scope._viewRouteParams().product_id), }; GAEAPI.get('deal/id', d, $scope).then(function(res) { if (res.ok == 1) { $scope.all_data = res.data; // $scope.data_tag = (e.data.product_set_array[0].product_tags).split(","); $scope.timeCountStart2($scope.all_data); console.log("sosososososoo :",res.data); $scope._dataArray = res.data.product_set_array[0]; $scope.data_video_id = $scope._dataArray.product_id; // if ($scope._dataArray.product_hightlight_video_embed != "") { // $scope._dataArray.product_image.unshift({ // image_url: $scope.imgPath + 'img-play.png', // product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed // }); // } $scope._dataArrayRelateProductId = $scope._dataArray.product_id; if ($scope._dataArray.product_tags != "") { $scope._dataArrayTags = $scope._dataArray.product_tags.split(","); } if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } if($scope._dataArray.product_referral_display.category != undefined){ $scope.productRelateTag($scope._dataArray.product_tags, $scope._dataArray.product_referral_display.category[0].referral_id); } if ($scope._dataArray.product_variant_array.length != 0) { if ($scope._dataArray.product_attribute.option_data.variant_array.length != 0 && $scope._dataArray.product_total_variant > 0) { // alert("x๊อบไข่สด"); var set_varia0 = $scope._dataArray.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < $scope._dataArray.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt($scope._dataArray.product_attribute.option_data.variant_array[i].price)) { set_varia0 = $scope._dataArray.product_attribute.option_data.variant_array[i].price; $scope.data_min = $scope._dataArray.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = $scope._dataArray.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ", $scope.data_min); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); $scope.buildVariantOption($scope._dataArray); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } console.log("dealsLists", $scope.all_data); } }); }; $scope.getData(); $scope.momentJs = { getDayString: function(timestamp) { return GAEAPI.time.dateFormat("D", timestamp); }, getMonthString: function(timestamp) { return GAEAPI.time.dateFormat("MMM", timestamp); }, getHoursString: function(timestamp) { return GAEAPI.time.dateFormat("hh", timestamp); }, getMinutesString: function(timestamp) { return GAEAPI.time.dateFormat("mm", timestamp); }, getSecondsString: function(timestamp) { return GAEAPI.time.dateFormat("ss", timestamp); }, getTimesString: function(timestamp) { return GAEAPI.time.dateFormat("hh : mm : ss", timestamp); } }; $scope.counter = 345600; $scope.timeDay = function() { var day = $scope.momentJs.getDayString($scope.counter); return day; } $scope.timeHours = function() { var hours = $scope.momentJs.getHoursString($scope.counter); return hours; } $scope.timeMinutes = function() { var minutes = $scope.momentJs.getMinutesString($scope.counter); return minutes; } $scope.timeSeconds = function() { var seconds = $scope.momentJs.getSecondsString($scope.counter); return seconds; } $scope.timeCount = function() { var time = $scope.momentJs.getTimesString($scope.counter); return time; } $scope.timeout_promise = null; $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.counter--; $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.time_out_deal = false; $scope.showPart = ""; $scope.countDown = function(settime) { var time_year = ""; var time_mount = ""; var time_date = ""; var time_hr = ""; var time_mi = ""; var time_se = ""; var timeA = ""; var timeB = ""; var timeC = ""; var timeDifference = ""; var timeDifference_temp = ""; var wan = ""; var l_wan = ""; var hour = ""; var l_hour = ""; var minute = ""; var second = ""; time_year = GAEAPI.time.dateFormat("YYYY", settime.product_lifetime.lifetime_end_time); time_mount = GAEAPI.time.dateFormat("M", settime.product_lifetime.lifetime_end_time); time_date = GAEAPI.time.dateFormat("D", settime.product_lifetime.lifetime_end_time); time_hr = GAEAPI.time.dateFormat("H", settime.product_lifetime.lifetime_end_time); time_mi = GAEAPI.time.dateFormat("m", settime.product_lifetime.lifetime_end_time); time_se = GAEAPI.time.dateFormat("s", settime.product_lifetime.lifetime_end_time); timeA = new Date(); /* วันเวลาปัจจุบัน */ timeB = new Date(time_year, (time_mount - 1), time_date, time_hr, time_mi, time_se, '0'); timeDifference = timeB.getTime() - timeA.getTime(); // console.log("timeDifference", timeDifference); if (timeDifference >= 0) { timeDifference = timeDifference / 1000; timeDifference = Math.floor(timeDifference); wan = Math.floor(timeDifference / 86400); l_wan = timeDifference % 86400; hour = Math.floor(l_wan / 3600); l_hour = l_wan % 3600; minute = Math.floor(l_hour / 60); second = l_hour % 60; $scope.showPart = wan + " วัน " + pad(hour, 2) + " ชั่วโมง " + pad(minute, 2) + " นาที " + pad(second, 2) + " วินาที"; if (wan == 0 && hour == 0 && minute == 0 && second == 0) {} // console.log("check_array", $scope.showPart); }else{ $scope.time_out_deal = true; } }; $scope.timeout_promise2 = null; $scope.timeCountStart2 = function(settime) { $scope.timeout_promise2 = $timeout(function() { $scope.countDown(settime); $scope.timeCountStart2(settime); }, 1000); }; $scope.data_min = []; $scope._dataArrayTags = []; $scope.data_video_id = false; $scope._getDataArray = function(id) { // $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_product_id': id }; GAEAPI.get('product/id', dataSend).then(function(res) { if (res.ok === 1) { console.log("sosososososoo :",res.data); $scope._dataArray = res.data; $scope.data_video_id = $scope._dataArray.product_id; // if ($scope._dataArray.product_hightlight_video_embed != "") { // $scope._dataArray.product_image.unshift({ // image_url: $scope.imgPath + 'img-play.png', // product_hightlight_video_embed: $scope._dataArray.product_hightlight_video_embed // }); // } $scope._dataArrayRelateProductId = res.data.product_id; if (res.data.product_tags != "") { $scope._dataArrayTags = res.data.product_tags.split(","); } if ($scope._dataArray.product_referral_display.category != undefined) { $scope.getRelation($scope._dataArray.product_referral_display.category[0].referral_id); } if($scope._dataArray.product_referral_display.category != undefined){ $scope.productRelateTag($scope._dataArray.product_tags, $scope._dataArray.product_referral_display.category[0].referral_id); } if (res.data.product_attribute.option_data != 0 && res.data.product_total_variant > 0) { if (res.data.product_attribute.option_data.variant_array.length != 0 && res.data.product_total_variant > 0) { // alert("x๊อบไข่สด"); var set_varia0 = res.data.product_attribute.option_data.variant_array[0].price; for (var i = 0; i < res.data.product_attribute.option_data.variant_array.length; i++) { if (parseInt(set_varia0) >= parseInt(res.data.product_attribute.option_data.variant_array[i].price)) { set_varia0 = res.data.product_attribute.option_data.variant_array[i].price; $scope.data_min = res.data.product_attribute.option_data.variant_array[i]; } } if ($scope.data_min.length == 0) { $scope.data_min = res.data.product_attribute.option_data.variant_array[0]; } console.log("iujdishjdskd : ", $scope.data_min); // $scope.buildVariantOption(e.data); // $scope.buildMultipleQuantity(e.data); $scope.buildVariantOption(res.data); } $scope._dataArray.product_price = $scope.data_min.price; $scope._dataArray.product_compare_price = $scope.data_min.compare_price; } } // $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } // $scope._getDataArray($scope._idUrl($scope._viewRouteParams().product_id)); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope._itemCarousel = function() { var elementName = '[data-key="' + $scope._uniqueKey + '"]'; var optionsParmas = { /*autoplay: (window.location.host !== 'localhost') ? true : false,*/ autoplay: false, slidesToShow: 1, slidesToScroll: 1, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; $rootScope.$on('repeatend', function() { if ($('[data-key="' + $scope._uniqueKey + '"]').not('.slick-initialized')) { $timeout(function() { $scope._itemCarousel(); }, 500); } }); $scope._data_qty_model = 1; $scope.viewQuantity = function() { return $(".d_qty.active.inin").find('input').val() || 1; }; $scope.decreseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 1) { e.val(i - 1); $scope._data_qty_selected = (i - 1); } return $scope._data_qty_selected; }; $scope.increseQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i > 98) { i = 98; } if (isNaN(i)) { i = 0; } e.val(i + 1); $scope._data_qty_selected = (i + 1); return $scope._data_qty_selected; }; $scope.watchQty = function(variant_key) { var e = angular.element('input[name="detail_qty"]'); if (typeof variant_key !== 'undefined') { e = angular.element('input[name="detail_qty"][variant-key="' + variant_key + '"]'); } var i = parseInt(e.val()); if (i <= 0 || typeof i == 'undefined' || isNaN(i)) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 1; e.val(1); }, 600); } if (i > 98) { var t = $timeout(function() { $timeout.cancel(t); $scope._data_qty_selected = 99; e.val(99); }, 600); } }; $scope.slickGoto = function(idx) { setTimeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickGoTo', idx); }, 100); }; $scope._slickGoLeft = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; $scope._slickGoRight = function() { $timeout(function() { $('[data-key="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.dataOption = []; $scope.dataVariants = []; $scope.buildVariantOption = function(objectData) { if (objectData.product_total_variant <= 0) { return; } $scope.dataOption = objectData.product_attribute.option_data.pclass_array; $scope.dataVariants = objectData.product_attribute.option_data.variant_array; // $scope.onClickVariantItems(); }; $scope.dataVariantsPick = []; $scope.buy_button = false; $scope.onClickVariantItems = function($index, option_id) { console.log("onSelectVariantItems:", $index, option_id); $scope.dataVariantsPick[$index] = option_id; $scope.buy_button = false; if ($scope.dataVariantsPick.length >= $scope.dataOption.length) { $scope.buy_button = true; $scope.findVariantsData($scope.dataVariantsPick); } }; $scope._saleState = { discount: 0 }; $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; $scope._saleState.discount = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; $scope._saleState.discount = 'percent'; } } return (sale > 0) ? sale : 0; } $scope._pricefullState = { pricefull: 0 }; $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; $scope._pricefullState.pricefull = 'not zero'; } else { $scope._pricefullState.pricefull = 'zero'; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.findVariantsData = function(variantsPick) { var count = 0; function compareArray(array_a, array) { if (!array) return false; if (array_a.length != array.length) return false; for (var i = 0, l = array_a.length; i < l; i++) { if (array_a[i] instanceof Array && array[i] instanceof Array) { if (!compareArray(array_a[i], array[i])) return false; } else if (array_a[i] != array[i]) { return false; } } return true; } var dataVariants = $scope.dataVariants; for (var i = 0; i < dataVariants.length; i++) { var optionJson = angular.fromJson(dataVariants[i].option_id_json); if (compareArray(variantsPick, optionJson)) { $scope._dataArray.product_id = dataVariants[i].product_id; $scope._dataArray.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = dataVariants[i].price; $scope._dataArray.product_compare_price = dataVariants[i].compare_price; $scope._dataArray.product_total_stock = dataVariants[i].total_stock; $scope.max_length = dataVariants[i].total_stock; break; } if (!compareArray(variantsPick, optionJson)) { count++; } if (count >= dataVariants.length) { // alert(count + " and " + dataVariants.length); // $scope.data.product_sku = dataVariants[i].sku; $scope._dataArray.product_price = 0; $scope._dataArray.product_compare_price = 0; } } }; $scope.data_viewTab = 1; $scope._viewTab = function(index) { $scope.data_viewTab = index; }; $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; //window.location.href='login'; }; $scope.makeVaraintsClick_Normal = function() { $timeout(function() { $('div.variantSelector').each(function(idx, obj) { $(this).find('span[data-index="' + idx + '"]').eq(0).click(); }); }, 2000); }; $scope.returnheight = function() { $(".cover_image_item").css("height", $(".cover_image_item").css("width")); $(".gallery_display").css("height", $(".cover_image_item").css("width")); /* $("iframe").css("height", $(".cover_image_item").css("width")); $("iframe").css("width", $(".cover_image_item").css("width")); */ } $scope.timeCountStart = function() { $scope.timeout_promise = $timeout(function() { $scope.returnheight(); $scope.timeCountStart(); }, 1000); } $scope.timeCountStart(); $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.showDebug = function() { return (typeof $routeParams.debug !== 'undefined') ? true : false; }; function pad(str, max) { str = str.toString(); return str.length < max ? pad("0" + str, max) : str; }; }; return promise; }); _ui_share_app.directive('productGridPick', function ($rootScope, $routeParams) { var templateName = 'productGridPick'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', referral: '=referral', referralname: '=referralname', limit: '=limit', imgpath: '@imgpath', name: '@name', shownotitem: '@shownotitem', imgcart : '@imgcart', sort : '@sort', datafont: '@datafont', textref: '@textref', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) {}; return promise; }); _ui_share_app.directive('productGridTypeA', function($rootScope, $routeParams) { var templateName = 'productGridTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._param = $routeParams.referral_type; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $('[data-on="finish-data"]').hide(); $('[data-on="finish-data"]').removeClass("data_loaded"); $('[data-on="finish-load"] span').text("Loading please wait..."); $timeout(function() { $('[data-on="finish-load"]').show(); $scope.getProduct(newValue); }, 300); } }); $scope.$watch('_param', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $('[data-on="finish-data"]').show(); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id) { $("img#loading-product").show(); $("img#img-no-product").hide(); if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option); $timeout(function() { if ($scope.productArray.length <= 0) { var shopInt = parseInt(CUR_THEME.shop_id()); if (shopInt === 509) { $("span#loading-product").hide(); $("img#loading-product").hide(); $("img#img-no-product").show(); } else { $('[data-on="finish-load"] span').text("ขออภัยไม่พบสินค้าที่เลือก"); } } }, 3000); }); }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* Broadcase Receiver */ $rootScope.$on('repeatend', function() { $('[data-on="finish-load"]').hide(); $('[data-on="finish-data"]').show(); $timeout(function() { $('[data-on="finish-data"]').addClass("data_loaded"); }, 300); }); $scope.is_optimize = true; /* view optimize image by size * @params {size} prefer image size (100,200,300,400 ?) * @params {image_url} image link */ $scope.viewOptimizeImage = function(size, image_url) { if (!$scope.is_optimize) { return image_url; } var a = image_url.split("/"); var b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; }; return promise; });_ui_share_app.directive('productGridTypeB', function($rootScope, $routeParams, $location) { var templateName = 'productGridTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { params: '=params', imgpath: '@imgpath', callback: '@callback', badgearray: '@badgeid', btnstyle: '@btnstyle', imgcart: '@imgcart', btntext: '@btntext', name: '@name', lang: '@lang', btnaddpdtext: '@btnaddpdtext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = CUR_THEME.file_url() + '../../assets/'; $scope.shopId = parseInt(CUR_THEME.shop_id()); console.log("btnstyle :", $scope.btnstyle); if ($scope.btnstyle == '' || $scope.btnstyle == undefined) { $scope.btnstyle = 'filled_button_round_xsmall'; } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.perpage_test = $routeParams.per_page; /* * params listener * @params (default) * @return function */ /*$scope.$watch('params', function (newValue, oldValue) { if (!newValue) return; });*/ $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 12; i++) { r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }], product_badge: [{ badge_id: 18 }], callback_array: true }); } return r; }; /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = "20"; $scope.productListSort = $scope._viewRouteParams().sort || "product_lastest_create"; $scope.$watch('perpage_test', function(newValue, oldValue) { if (newValue) { $scope.per_page = newValue; } }); $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; $scope.getProduct = function() { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; /* Check: Search */ if (typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== "") { option.search = $scope._viewRouteParams().search; } /* Check: referral */ if (typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0) { option.referral_id_array = [$scope._viewRouteParams().referral_id]; } /* Check: badge */ if (typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != "") { /* Check Badge from URL */ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit, function(i, k) { option.badge_id_array.push(i); }); } else if ($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false) { /* Check Badge from component (multibadge) */ if ($scope.badgeid.indexOf(',') == -1) { var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i, k) { var test = i.trim(); if (option.badge_id_array.indexOf(test) == -1) { /* check exist */ option.badge_id_array.push(i.trim()); } }); } else { /* Check Badge from component (1 badge) */ var test = $scope.badgeid.trim(); if (option.badge_id_array.indexOf(test) == -1) { /* check exist */ option.badge_id_array.push($scope.badgeid.trim()); } } } /* Check: sort by */ var sortBy = 'product_lastest_create'; if (typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != "") { var r = $scope._viewRouteParams().sort; switch (r) { case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var dataSend = { 'cur_page': (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 20, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { if (e.data.dataList.length > 0) { $scope.productArray = e.data.dataList; $scope.buildPaginationParameter(e.data); } else { if (typeof $scope.callback !== 'undefined' && $scope.callback !== '') { $scope.productArray = $scope.watchCallbackArray(); } } /*console.log("productArray", $scope.productArray);*/ if ($("#feature-product").hasClass('hide')) { $('#feature-product').removeClass('hide'); } } $scope.productState.load = false; $scope.productState.done = true; /*console.log("Share Component Get All", dataSend, option, e);*/ }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function(data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function(total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener (sortby) * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; /** * select listener (item per page) * @params model (string) * @return event */ $scope.displayChange = function(e) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } paramsObj.page = '1'; if (e == "") { /* paramsObj.per_page = 20 ;*/ } else { paramsObj.per_page = e; } $timeout(function() { $location.path(pathStr).search(paramsObj); }, 300); }; $scope.buildFilterUrl = function(exceptionalKey) { var a = ''; angular.forEach($routeParams, function(item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i) { return parseInt(i) || false; }; $scope.printSelected = function(a) { if ($routeParams.sort == a) { return " selected"; } return " "; }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* when route change success => do something */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { console.log("pageChangedSuccess", current); $scope.getProduct(); }); }; return promise; }); _ui_share_app.directive('productGridTypeBBadge', function ($rootScope, $routeParams, $location) { var templateName = 'productGridTypeBBadge'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { params:'=params', imgpath: '@imgpath', callback: '@callback', badgearray: '@badgeid', btnstyle : '@btnstyle', imgcart : '@imgcart', btntext : '@btntext', name : '@name', lang: '@lang', btnaddpdtext: '@btnaddpdtext', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.shopId = parseInt(CUR_THEME.shop_id()); console.log("btnstyle :",$scope.btnstyle); if($scope.btnstyle == '' || $scope.btnstyle == undefined) { $scope.btnstyle = 'filled_button_round_xsmall'; } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; $scope.perpage_test = $routeParams.per_page; /* * params listener * @params (default) * @return function */ /*$scope.$watch('params', function (newValue, oldValue) { if (!newValue) return; });*/ $scope.fetchTime = 1; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getProduct(); }, 300); }; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 12; i++){ r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}], product_badge:[{badge_id:18}], callback_array:true }); } return r; }; /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = "20"; $scope.productListSort = $scope._viewRouteParams().sort || "product_lastest_create"; $scope.$watch('perpage_test', function (newValue, oldValue) { if(newValue){ $scope.per_page = newValue; } }); $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; $scope.all_page = true; $scope.getProduct = function () { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; /* Check: Search */ if(typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== ""){ option.search = $scope._viewRouteParams().search; } /* Check: referral */ if(typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0){ option.referral_id_array = [$scope._viewRouteParams().referral_id]; } /* Check: badge */ if(typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != ""){ /* Check Badge from URL */ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit,function(i,k){ option.badge_id_array.push(i); }); } else if($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false){ /* Check Badge from component (multibadge) */ if($scope.badgeid.indexOf(',') == -1){ var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i,k){ var test = i.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push(i.trim()); } }); } else { /* Check Badge from component (1 badge) */ var test = $scope.badgeid.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push($scope.badgeid.trim()); } } } /* Check: sort by */ var sortBy = 'product_lastest_create'; if(typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != ""){ var r = $scope._viewRouteParams().sort; switch(r){ case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var dataSend = { 'cur_page': (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 20, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { if ($scope.productArray.length) { var curData = $scope.productArray; $scope.productArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } // $scope.productArray = e.data.dataList; // $scope.buildPaginationParameter(e.data); } else{ $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } /*console.log("productArray", $scope.productArray);*/ // if($("#feature-product").hasClass('hide')){ // $('#feature-product').removeClass('hide'); // } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } $scope.productState.load = false; $scope.productState.done = true; /*console.log("Share Component Get All", dataSend, option, e);*/ }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function (data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function (total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener (sortby) * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel){ var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/product-badge-list'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().badge != 'undefined' && $location.search().badge != "") { otherParams += "&badge=" + $location.search().badge; paramsObj.badge = $location.search().badge; } paramsObj.sort = sortbyModel; $timeout(function () { $scope.productListSort=sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; /** * select listener (item per page) * @params model (string) * @return event */ $scope.displayChange = function(e){ var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/product-badge-list'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().badge != 'undefined' && $location.search().badge != "") { otherParams += "&badge=" + $location.search().badge; paramsObj.badge = $location.search().badge; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } paramsObj.page = '1'; if(e == ""){ /* paramsObj.per_page = 20 ;*/ }else{ paramsObj.per_page = e; } $timeout(function () { $location.path(pathStr).search(paramsObj); }, 300); }; $scope.buildFilterUrl = function(exceptionalKey){ var a = ''; angular.forEach($routeParams, function (item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i){ return parseInt(i) || false; }; $scope.printSelected = function(a){ if($routeParams.sort == a){ return " selected"; } return " "; }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* when route change success => do something */ // $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { // console.log("pageChangedSuccess", current); // $scope.getProduct(); // }); }; return promise; }); _ui_share_app.directive('productGridTypeBa', function ($rootScope, $routeParams, $location) { var templateName = 'productGridTypeBa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { params:'=params', imgpath: '@imgpath', callback: '@callback', badgearray: '@badgeid', btnstyle : '@btnstyle', imgcart : '@imgcart', btntext : '@btntext', name : '@name', btnaddpdtext: '@btnaddpdtext', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.shopId = parseInt(CUR_THEME.shop_id()); console.log("btnstyle :",$scope.btnstyle); if($scope.btnstyle == '' || $scope.btnstyle == undefined) { $scope.btnstyle = 'filled_button_round_xsmall'; } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; $scope.perpage_test = $routeParams.per_page; /* * params listener * @params (default) * @return function */ /*$scope.$watch('params', function (newValue, oldValue) { if (!newValue) return; });*/ $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 12; i++){ r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}], product_badge:[{badge_id:18}], callback_array:true }); } return r; }; /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = "20"; $scope.productListSort = $scope._viewRouteParams().sort || ""; $scope.$watch('perpage_test', function (newValue, oldValue) { if(newValue){ $scope.per_page = newValue; } }); $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; $scope.getProduct = function () { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; /* Check: Search */ if(typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== ""){ option.search = $scope._viewRouteParams().search; } /* Check: referral */ if(typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0){ option.referral_id_array = [$scope._viewRouteParams().referral_id]; } /* Check: badge */ if(typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != ""){ /* Check Badge from URL */ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit,function(i,k){ option.badge_id_array.push(i); }); } else if($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false){ /* Check Badge from component (multibadge) */ if($scope.badgeid.indexOf(',') == -1){ var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i,k){ var test = i.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push(i.trim()); } }); } else { /* Check Badge from component (1 badge) */ var test = $scope.badgeid.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push($scope.badgeid.trim()); } } } /* Check: sort by */ var sortBy = 'product_lastest_create'; if(typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != ""){ var r = $scope._viewRouteParams().sort; switch(r){ case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var dataSend = { 'cur_page': (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 20, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { if(e.data.dataList.length > 0){ $scope.productArray = e.data.dataList; $scope.buildPaginationParameter(e.data); } else { if(typeof $scope.callback !== 'undefined' && $scope.callback !== ''){ $scope.productArray = $scope.watchCallbackArray(); } } /*console.log("productArray", $scope.productArray);*/ if($("#feature-product").hasClass('hide')){ $('#feature-product').removeClass('hide'); } } $scope.productState.load = false; $scope.productState.done = true; /*console.log("Share Component Get All", dataSend, option, e);*/ }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function (data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function (total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener (sortby) * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel){ var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('promotion') !== -1) ? '/promotion' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } paramsObj.sort = sortbyModel; $timeout(function () { $scope.productListSort=sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; /** * select listener (item per page) * @params model (string) * @return event */ $scope.displayChange = function(e){ var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('promotion') !== -1) ? '/promotion' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } paramsObj.page = '1'; if(e == ""){ /*paramsObj.per_page = 20;*/ } else { paramsObj.per_page = e; } $timeout(function () { $location.path(pathStr).search(paramsObj); }, 300); }; $scope.buildFilterUrl = function(exceptionalKey){ var a = ''; angular.forEach($routeParams, function (item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i){ return parseInt(i) || false; }; $scope.printSelected = function(a){ if($routeParams.sort == a){ return " selected"; } return " "; }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* when route change success => do something */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("pageChangedSuccess", current); $scope.getProduct(); }); }; return promise; }); _ui_share_app.directive('productGridTypeBb', function ($rootScope, $routeParams, $location) { var templateName = 'productGridTypeBb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { params:'=params', imgpath: '@imgpath', callback: '@callback', badgearray: '@badgeid', btnstyle : '@btnstyle', imgcart : '@imgcart', btntext : '@btntext', name : '@name', lang: '@lang', btnaddpdtext: '@btnaddpdtext', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.shopId = parseInt(CUR_THEME.shop_id()); $scope.loadMore_is_load = false; console.log("btnstyle :",$scope.btnstyle); if($scope.btnstyle == '' || $scope.btnstyle == undefined) { $scope.btnstyle = 'filled_button_round_xsmall'; } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; $scope.perpage_test = $routeParams.per_page; /* * params listener * @params (default) * @return function */ /*$scope.$watch('params', function (newValue, oldValue) { if (!newValue) return; });*/ $scope.fetchTime = 1; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getProduct(); }, 300); }; $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 12; i++){ r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}], product_badge:[{badge_id:18}], callback_array:true }); } return r; }; /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = "20"; $scope.productListSort = $scope._viewRouteParams().sort || "product_lastest_create"; $scope.$watch('perpage_test', function (newValue, oldValue) { if(newValue){ $scope.per_page = newValue; } }); $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; $scope.all_page = true; $scope.getProduct = function () { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; /* Check: Search */ if(typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== ""){ option.search = $scope._viewRouteParams().search; } /* Check: referral */ if(typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0){ option.referral_id_array = [$scope._viewRouteParams().referral_id]; } /* Check: badge */ if(typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != ""){ /* Check Badge from URL */ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit,function(i,k){ option.badge_id_array.push(i); }); } else if($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false){ /* Check Badge from component (multibadge) */ if($scope.badgeid.indexOf(',') == -1){ var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i,k){ var test = i.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push(i.trim()); } }); } else { /* Check Badge from component (1 badge) */ var test = $scope.badgeid.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push($scope.badgeid.trim()); } } } /* Check: sort by */ var sortBy = 'product_lastest_create'; if(typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != ""){ var r = $scope._viewRouteParams().sort; switch(r){ case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var dataSend = { 'cur_page': (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 20, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { if ($scope.productArray.length) { var curData = $scope.productArray; $scope.productArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } // $scope.productArray = e.data.dataList; // $scope.buildPaginationParameter(e.data); } else{ $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } /*console.log("productArray", $scope.productArray);*/ // if($("#feature-product").hasClass('hide')){ // $('#feature-product').removeClass('hide'); // } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } $scope.productState.load = false; $scope.productState.done = true; /*console.log("Share Component Get All", dataSend, option, e);*/ }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function (data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function (total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener (sortby) * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel){ var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } paramsObj.sort = sortbyModel; $timeout(function () { $scope.productListSort=sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; /** * select listener (item per page) * @params model (string) * @return event */ $scope.displayChange = function(e){ var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } paramsObj.page = '1'; if(e == ""){ /* paramsObj.per_page = 20 ;*/ }else{ paramsObj.per_page = e; } $timeout(function () { $location.path(pathStr).search(paramsObj); }, 300); }; $scope.buildFilterUrl = function(exceptionalKey){ var a = ''; angular.forEach($routeParams, function (item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i){ return parseInt(i) || false; }; $scope.printSelected = function(a){ if($routeParams.sort == a){ return " selected"; } return " "; }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* when route change success => do something */ // $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { // console.log("pageChangedSuccess", current); // $scope.getProduct(); // }); }; return promise; }); _ui_share_app.directive('productGridTypeCe', function ($rootScope, $routeParams, $location) { var templateName = 'productGridTypeCe'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { params:'=params', imgpath: '@imgpath', callback: '@callback', badgearray: '@badgeid', btnstyle : '@btnstyle', imgcart : '@imgcart', btntext : '@btntext', name : '@name', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.shopId = parseInt(CUR_THEME.shop_id()); console.log("btnstyle :",$scope.btnstyle); if($scope.btnstyle == '' || $scope.btnstyle == undefined) { $scope.btnstyle = 'filled_button_round_xsmall'; } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; $scope.perpage_test = $routeParams.per_page; /* * params listener * @params (default) * @return function */ /*$scope.$watch('params', function (newValue, oldValue) { if (!newValue) return; });*/ $scope.watchCallbackArray = function(){ var r = []; for(var i = 0; i < 12; i++){ r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image:[{image_url:'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif'}], product_badge:[{badge_id:18}], callback_array:true }); } return r; }; /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = "20"; // $scope.productListSort = $scope._viewRouteParams().sort || ""; $scope.$watch('perpage_test', function (newValue, oldValue) { if(newValue){ $scope.per_page = newValue; } }); $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; $scope.productListSort = $scope._viewRouteParams().sort || "product_lastest_create"; $scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.getProduct = function () { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; /* Check: Search */ if(typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== ""){ option.search = $scope._viewRouteParams().search; } /* Check: referral */ if(typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0){ option.referral_id_array = [$scope._viewRouteParams().referral_id]; } /* Check: badge */ if(typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != ""){ /* Check Badge from URL */ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit,function(i,k){ option.badge_id_array.push(i); }); } else if($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false){ /* Check Badge from component (multibadge) */ if($scope.badgeid.indexOf(',') == -1){ var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i,k){ var test = i.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push(i.trim()); } }); } else { /* Check Badge from component (1 badge) */ var test = $scope.badgeid.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push($scope.badgeid.trim()); } } } /* Check: sort by */ var sortBy = 'product_lastest_create'; if(typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != ""){ var r = $scope._viewRouteParams().sort; switch(r){ case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var dataSend = { 'cur_page': (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 20, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { if(e.data.dataList.length > 0){ $scope.productArray = e.data.dataList; $scope.buildPaginationParameter(e.data); } else { if(typeof $scope.callback !== 'undefined' && $scope.callback !== ''){ $scope.productArray = $scope.watchCallbackArray(); } } /*console.log("productArray", $scope.productArray);*/ if($("#feature-product").hasClass('hide')){ $('#feature-product').removeClass('hide'); } } $scope.productState.load = false; $scope.productState.done = true; /*console.log("Share Component Get All", dataSend, option, e);*/ }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function (data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function (total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener (sortby) * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel){ var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } paramsObj.sort = sortbyModel; $timeout(function () { $scope.productListSort=sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; /** * select listener (item per page) * @params model (string) * @return event */ $scope.displayChange = function(e){ var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } paramsObj.page = '1'; if(e == ""){ /* paramsObj.per_page = 20 ;*/ }else{ paramsObj.per_page = e; } $timeout(function () { $location.path(pathStr).search(paramsObj); }, 300); }; $scope.buildFilterUrl = function(exceptionalKey){ var a = ''; angular.forEach($routeParams, function (item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i){ return parseInt(i) || false; }; $scope.printSelected = function(a){ if($routeParams.sort == a){ return " selected"; } return " "; }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* when route change success => do something */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("pageChangedSuccess", current); $scope.getProduct(); }); }; return promise; }); _ui_share_app.directive('productGridTypeD', function ($rootScope, $routeParams) { var templateName = 'productGridTypeD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', shownotitem : '@shownotitem', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option); }); }; $scope.buyButton = false; if (CUR_THEME.data.shop_id == "594") { $scope.buyButton = true; } if (CUR_THEME.data.shop_id == "523") { $scope.buyButton = true; } $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productGridTypeDa', function($rootScope, $routeParams) { var templateName = 'productGridTypeDa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', shownotitem: '@shownotitem', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_sortby': "root_category_index_asc", 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option); }); }; $scope.buyButton = false; if (CUR_THEME.data.shop_id == "594") { $scope.buyButton = true; } if (CUR_THEME.data.shop_id == "523") { $scope.buyButton = true; } $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productGridTypeDb', function($rootScope, $routeParams) { var templateName = 'productGridTypeDb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', shownotitem: '@shownotitem', datafont: '@datafont', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout,$location, $interval, $q, $window) { /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { // alert(newValue); $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option); }); }; $scope.buyButton = false; if (CUR_THEME.data.shop_id == "594") { $scope.buyButton = true; } if (CUR_THEME.data.shop_id == "523") { $scope.buyButton = true; } $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productGridTypeE', function($rootScope, $routeParams) { var templateName = 'productGridTypeE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', imgcart: '@imgcart' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option, e); if (e.data.total_rows <= 0) { $scope.getReferal(ref_id); } }); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Fetch referral list */ $scope.referralArray = []; $scope.getReferal = function(ref_id) { var d = { txt_referral_type_id: 11, txt_parent_id: ref_id }; GAEAPI.get('referral/map', d, $scope).then(function(e) { $scope.referralArray = e.data; }); }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; }); _ui_share_app.directive('productGridTypeEb', function ($rootScope, $routeParams) { var templateName = 'productGridTypeEb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._param = $routeParams.referral_type; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $('[data-on="finish-data"]').hide(); $('[data-on="finish-data"]').removeClass("data_loaded"); $('[data-on="finish-load"] span').text("Loading please wait..."); $timeout(function(){ $('[data-on="finish-load"]').show(); $scope.getProduct(newValue); },300); } }); $scope.$watch('_param', function (newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $('[data-on="finish-data"]').show(); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option); $timeout(function(){ if($scope.productArray.length <= 0){ $('[data-on="finish-load"] span').text("ขออภัยไม่พบสินค้าที่เลือก"); } },1000); }); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* Broadcase Receiver */ $rootScope.$on('repeatend', function() { $('[data-on="finish-load"]').hide(); $('[data-on="finish-data"]').show(); $timeout(function(){ $('[data-on="finish-data"]').addClass("data_loaded"); }, 300); }); $scope.is_optimize = true; /* view optimize image by size * @params {size} prefer image size (100,200,300,400 ?) * @params {image_url} image link */ $scope.viewOptimizeImage = function(size,image_url){ if(!$scope.is_optimize){ return image_url; } var a = image_url.split("/"); var b = a[a.length - 1]; a[a.length - 1] = 't'+size+'_' + b; return a.join("/"); }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; }); _ui_share_app.directive('productGridTypeEc', function($rootScope, $routeParams) { var templateName = 'productGridTypeEc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option, e); if (e.data.total_rows <= 0) { $scope.getReferal(ref_id); } }); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Fetch referral list */ $scope.referralArray = []; $scope.getReferal = function(ref_id) { var d = { txt_referral_type_id: 11, txt_parent_id: ref_id }; GAEAPI.get('referral/map', d).then(function(e) { $scope.referralArray = e.data; }); }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productGridTypeEd', function($rootScope, $routeParams) { var templateName = 'productGridTypeEd'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* viewRouteParams */ $scope._viewRouteParams = function() { return $routeParams; }; /* viewRouteParams */ /* Update state */ $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } /* Update state */ /* Load More */ $scope.page = 1; $scope.sort_ = $scope.sort || "product_lifetime_start_asc"; // alert($scope.sort_); $scope.state_load_more = true; $scope.load_more_is_load = false; $scope.loadMore = function() { $scope.page++; $scope.load_more_is_load = true; $timeout(function() { $scope.getProduct($routeParams.referral_id, 0); }, 300); }; /* Load More */ /* state */ $scope.productState = { load: true, done: false }; /* state */ /* array_product */ $scope.productArray = []; /* array_product */ /* get products */ $scope.getProduct = function(ref_id) { console.log("getProduct : ref_id : ", ref_id); if ($scope.page == 1) { $scope.productState = $scope.StateData(true, false); } var option = { 'badge_id_array': [18], 'referral_id_array': [ref_id] }; var dataSend = { 'cur_page': $scope.page, 'per_page': $scope.limit, 'txt_sortby': $scope.sort_, 'txt_filter_json': JSON.stringify(option) }; console.log("getProduct : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { console.log("getProduct : output : ", output); if (output.ok == 1) { console.log("getProduct : ok : 1", output.ok); if ($scope.productArray.length) { var data_output = $scope.productArray; $scope.productArray = data_output.concat(output.data.dataList); if (output.data.total_rows <= $scope.productArray.length) { $scope.state_load_more = false; } else { $scope.state_load_more = true; } } else { $scope.productArray = output.data.dataList; if (output.data.total_rows <= $scope.productArray.length) { $scope.state_load_more = false; } else { $scope.state_load_more = true; } } } else { console.log("getProduct : ok : 2", output.ok); } if ($scope.page > 1) { $scope.load_more_is_load = false; } console.log("getProduct : output : ", output); if ($scope.page == 1) { $scope.productState = $scope.StateData(false, true); } }); }; /* get products */ $scope.$watch('referral', function(newValue, oldValue) { console.log("watch : newValue ", newValue); console.log("watch : oldValue ", oldValue); if (newValue) { $scope.getProduct(newValue); } else { return; } }); }; return promise; });_ui_share_app.directive('productGridTypeEe', function($rootScope, $routeParams) { var templateName = 'productGridTypeEe'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* viewRouteParams */ $scope._viewRouteParams = function() { return $routeParams; }; /* viewRouteParams */ /* Update state */ $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } /* Update state */ /* Load More */ $scope.page = 1; $scope.state_load_more = true; $scope.load_more_is_load = false; $scope.loadMore = function() { $scope.page++; $scope.load_more_is_load = true; $timeout(function() { $scope.getProduct($routeParams.referral_id, 0); }, 300); }; /* Load More */ /* state */ $scope.productState = { load: true, done: false }; /* state */ /* array_product */ $scope.productArray = []; /* array_product */ /* get products */ $scope.getProduct = function(ref_id) { console.log("getProduct : ref_id : ", ref_id); if ($scope.page == 1) { $scope.productState = $scope.StateData(true, false); } var option = { 'badge_id_array': [18], 'referral_id_array': [ref_id] }; var dataSend = { 'cur_page': $scope.page, 'per_page': $scope.limit, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; console.log("getProduct : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { console.log("getProduct : output : ", output); if (output.ok == 1) { console.log("getProduct : ok : ", output.ok); if ($scope.productArray.length) { var data_output = $scope.productArray; $scope.productArray = data_output.concat(output.data.dataList); if (output.data.total_rows <= $scope.productArray.length) { $scope.state_load_more = false; } else { $scope.state_load_more = true; } } else { $scope.productArray = output.data.dataList; if (output.data.total_rows <= $scope.productArray.length) { $scope.state_load_more = false; } else { $scope.state_load_more = true; } } } else { console.log("getProduct : ok : ", output.ok); } if ($scope.page > 1) { $scope.load_more_is_load = false; } console.log("getProduct : output : ", output); if ($scope.page == 1) { $scope.productState = $scope.StateData(false, true); } }); }; /* get products */ $scope.$watch('referral', function(newValue, oldValue) { console.log("watch : newValue ", newValue); console.log("watch : oldValue ", oldValue); if (newValue) { $scope.getProduct(newValue); } else { return; } }); }; return promise; });_ui_share_app.directive('productGridTypeEf', function($rootScope, $routeParams) { var templateName = 'productGridTypeEf'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option, e); if (e.data.total_rows <= 0) { $scope.getReferal(ref_id); } }); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Fetch referral list */ $scope.referralArray = []; $scope.getReferal = function(ref_id) { var d = { txt_referral_type_id: 11, txt_parent_id: ref_id }; GAEAPI.get('referral/map', d).then(function(e) { $scope.referralArray = e.data; }); }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productGridTypeEg', function($rootScope, $routeParams, $location) { var templateName = 'productGridTypeEg'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', limit: '@limit', name: '@name', sort: '@sort', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ /* Load More */ /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.fetchTime = 1; $scope.all_page = true; $scope.getProduct = function() { // alert("sdsds :"+$scope.sort); if (typeof $scope.referral === 'undefined' || $scope.referral === 0) { // alert("1"); $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = false; return; } /* Set loading state */ // $scope.productState.load = true; // $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [$scope.referral]; if ($scope.sort != '' || typeof $scope.sort != 'undefined') { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.limit, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; } else { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 8, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(option) }; } /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { $scope.productState.load = false; $scope.productState.done = true; if ($scope.productArray.length) { // $scope.productArray = e.data.dataList; var curData = $scope.productArray; $scope.productArray = curData.concat(e.data.dataList); console.log("aswiadjadja 2:",$scope.productArray); if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } }else { $scope.productArray = e.data.dataList; console.log("aswiadjadja 1:",$scope.productArray); if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } console.log("Share Component Get", dataSend, option, e); if (e.data.total_rows <= 0) { $scope.getReferal($scope.referral); } }); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Fetch referral list */ $scope.referralArray = []; $scope.getReferal = function(ref_id) { var d = { txt_referral_type_id: 11, txt_parent_id: ref_id }; GAEAPI.get('referral/map', d).then(function(e) { $scope.referralArray = e.data; }); }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.getProduct(); $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getProduct(); }, 300); }; // $scope.$watch('referral', function(newValue, oldValue) { // if (!newValue) return; // if (newValue != 0) { // $scope.getProduct(); // } // }); // $scope.$watch('sort', function(newValue, oldValue) { // if (!newValue){ // return; // } // if (newValue != 0) { // // alert($scope.referral); // $scope.getProduct($scope.referral,1); // } // }); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.productState.done && $scope.productArray.length) { $scope.productArray = []; $scope.fetchTime = 1; $scope.all_page = true; $scope.productState.load = true; $scope.productState.done = false; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.productState.load = true; $scope.productState.done = false; if (!$scope.productState.done && !$scope.productArray.length) { $timeout(function() { // alert("asasasa"); $scope.getProduct(); }, 100); }else{ $timeout(function() { // alert("asasasa"); $scope.getProduct(); }, 100); } }); }; return promise; });_ui_share_app.directive('productGridTypeEh', function($rootScope, $routeParams, $location) { var templateName = 'productGridTypeEh'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', imgcart: '@imgcart', textref: '@textref', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * view current routeParams * @params (default) * @return function */ $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.FetchDisplayCategory(); $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/category-lists'; var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: $scope.viewRouteParams().referral_id, referral_type: $scope.viewRouteParams().referral_type, /* product in this category/filter cat */ /* sortby */ }; paramsObj.referral_id = path.referral_id; paramsObj.root_id = path.root_id; paramsObj.referral_type = "category"; paramsObj.sort = sortbyModel; $timeout(function() { $location.path(pathStr).search(paramsObj); }, 300); }; /* * params listener * @params (default) * @return function */ /* $scope.$watch('referral', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); */ /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option, e); if (e.data.total_rows <= 0) { $scope.getReferal(ref_id); } }); }; /* product/lists Update */ $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.consoleLog = function(name, data) { var consoleState = true; if (consoleState) { console.log(name, data); } }; $scope.badge = 0; $scope.totalRows = 0; $scope.dataLoadMoreStatus = { show: false, data: false }; $scope.curPage = 1; $scope.perPage = (typeof $scope.limit !== 'undefined' && typeof $scope.limit !== '') ? parseInt($scope.limit) : 20; $scope.txtSortby = $scope.viewRouteParams().sort || 'product_title_a-z'; $scope.filterSortData = $scope.viewRouteParams().sort || 'product_title_a-z'; $scope.dataProduct = []; $scope.dataProductStatus = { load: true, done: false }; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 1000); }; $scope.createArrayBadgeId = function(badge_id, callback) { $scope.consoleLog("createArrayBadgeId : badge_id : ", badge_id); var array_badge = []; array_badge.push(badge_id); callback(array_badge); }; $scope.createArrayReferralId = function(referral_id, callback) { $scope.consoleLog("createArrayReferralId : referral_id : ", referral_id); var array_referral = []; array_referral.push(referral_id); callback(array_referral); }; $scope.getProductInCategoryId = function(cur_page, per_page, txt_sortby, array_referral, array_badge, callback) { var productInCategoryStatus = false; var productTotalRows = 0; var productList = []; var filter_json = { "referral_id_array": array_referral } var dataSend = { 'cur_page': cur_page, 'per_page': per_page, 'txt_sortby': txt_sortby, 'txt_filter_json': JSON.stringify(filter_json), }; $scope.consoleLog("getProductInCategoryId : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { $scope.consoleLog("getProductInCategoryId : output : ", output); if (output.ok == 1) { productInCategoryStatus = $scope.stateMore(true); productTotalRows = output.data.total_rows; productList = output.data.dataList; callback(productInCategoryStatus, productTotalRows, productList); } else { callback(productInCategoryStatus, productTotalRows, productList); } $scope.data_product_done = true; }); }; $scope.stateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.stateMore = function(_load_in) { var State = _load_in; return State; }; $scope.loadMore = function() { var cur_page = $scope.curPage - 1; $scope.consoleLog("loadMore : dataProductArray : ", $scope.dataProductArray); $scope.consoleLog("loadMore : dataProductArray : length : ", $scope.dataProductArray.length); $scope.consoleLog("loadMore : cur_page : ", cur_page); $scope.dataLoadMoreStatus.data = $scope.stateMore(true); if ($scope.curPage <= $scope.dataProductArray.length) { $scope.curPage++; var oldData = $scope.dataProduct; $scope.dataProduct = oldData.concat($scope.dataProductArray[cur_page]); $scope.dataLoadMoreStatus.data = $scope.stateMore(false); if ($scope.dataProduct.length < $scope.dataProductTotalRows) { $scope.dataLoadMoreStatus.show = $scope.stateMore(true); } else { $scope.dataLoadMoreStatus.show = $scope.stateMore(false); } } else { setTimeout(function() { $scope.loadMore(); }, 1000); } /* BACKUP */ /* $scope.curPage++; $scope.dataLoadMoreStatus.data = $scope.stateMore(true); $scope.createArrayReferralId(parseInt($scope.viewRouteParams().referral_id), function(array_referral) { $scope.consoleLog("loadMore : createArrayReferralId : array_referral : ", array_referral); $scope.createArrayBadgeId($scope.badge, function(array_badge) { $scope.getProductInCategoryId($scope.curPage, $scope.perPage, $scope.txtSortby, array_referral, array_badge, function(productInCategoryStatus, productTotalRows, productList) { $scope.consoleLog("loadMore : createArrayReferralId : getProductInCategoryId : productInCategoryStatus : ", productInCategoryStatus); $scope.consoleLog("loadMore : createArrayReferralId : getProductInCategoryId : productList : ", productList); var oldData = $scope.dataProduct; $scope.dataProduct = oldData.concat(productList); $scope.dataLoadMoreStatus.data = $scope.stateMore(false); $scope.consoleLog("loadMore : createArrayReferralId : getProductInCategoryId : productTotalRows : ", productTotalRows); $scope.totalRows = productTotalRows; if ($scope.dataProduct.length < productTotalRows) { $scope.dataLoadMoreStatus.show = $scope.stateMore(true); } else { $scope.dataLoadMoreStatus.show = $scope.stateMore(false); } }); }); }); */ /* BACKUP */ }; $scope.dataProductArray = []; $scope.dataProductLength = 0; $scope.dataProductTotalRows = 0; $scope.loopGetAPI = function(cur_page, product_total_rows) { $scope.consoleLog("loopGetAPI : dataProductLength : ", $scope.dataProductLength); $scope.consoleLog("loopGetAPI : cur_page : ", cur_page); $scope.consoleLog("loopGetAPI : product_total_rows : ", product_total_rows); if ($scope.dataProductLength < product_total_rows) { $scope.createArrayReferralId(parseInt($scope.viewRouteParams().referral_id), function(array_referral) { $scope.consoleLog("loopGetAPI : createArrayReferralId : array_referral : ", array_referral); $scope.createArrayBadgeId($scope.badge, function(array_badge) { $scope.consoleLog("loopGetAPI : createArrayBadgeId : array_badge : ", array_badge); cur_page = cur_page + 1 $scope.getProductInCategoryId(cur_page, $scope.perPage, $scope.txtSortby, array_referral, array_badge, function(productInCategoryStatus, productTotalRows, productList) { $scope.consoleLog("loopGetAPI : createArrayReferralId : getProductInCategoryId : productInCategoryStatus : ", productInCategoryStatus); $scope.consoleLog("loopGetAPI : createArrayReferralId : getProductInCategoryId : productList : ", productList); $scope.consoleLog("loopGetAPI : createArrayReferralId : getProductInCategoryId : productTotalRows : ", productTotalRows); $scope.dataProductTotalRows = productTotalRows; $scope.dataProductArray.push(productList); $scope.consoleLog("loopGetAPI : createArrayReferralId : getProductInCategoryId : dataProductArray : ", $scope.dataProductArray); $scope.dataProductLength = $scope.dataProductLength + productList.length; $scope.consoleLog("loopGetAPI : createArrayReferralId : getProductInCategoryId : dataProductLength : ", $scope.dataProductLength); if ($scope.dataProductLength < productTotalRows) { $scope.loopGetAPI(cur_page, productTotalRows); } }) }); }); } }; $scope.data_product_done = false; $scope.getData = function() { $scope.createArrayReferralId(parseInt($scope.viewRouteParams().referral_id), function(array_referral) { $scope.consoleLog("getData : createArrayReferralId : array_referral : ", array_referral); $scope.dataProductStatus = $scope.stateData(true, false); $scope.createArrayBadgeId($scope.badge, function(array_badge) { $scope.consoleLog("getData : createArrayBadgeId : array_badge : ", array_badge); $scope.getProductInCategoryId($scope.curPage, $scope.perPage, $scope.txtSortby, array_referral, array_badge, function(productInCategoryStatus, productTotalRows, productList) { $scope.consoleLog("getData : createArrayReferralId : getProductInCategoryId : productInCategoryStatus : ", productInCategoryStatus); $scope.consoleLog("getData : createArrayReferralId : getProductInCategoryId : productList : ", productList); $scope.consoleLog("getData : createArrayReferralId : getProductInCategoryId : productTotalRows : ", productTotalRows); $scope.dataProduct = productList; $scope.dataProductLength = productList.length; if (productList.length < productTotalRows) { $scope.dataLoadMoreStatus.show = $scope.stateMore(true); } else { $scope.dataLoadMoreStatus.show = $scope.stateMore(false); } $scope.totalRows = productTotalRows; $scope.dataProductStatus = $scope.stateData(false, true); /* loopData */ $scope.loopGetAPI($scope.curPage, productTotalRows); /* loopData */ }); }); }); } $scope.getData(); /* $scope.pathChange = function() { var path = { root_id: $scope.viewRouteParams().root_id, referral_id: $scope.viewRouteParams().referral_id, referral_type: $scope.viewRouteParams().referral_type, sort: $scope.txtSortby, }; var strHref = 'category-lists'; if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '?referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '&root_id=' + path.root_id; } else { delete path.root_id; } if (typeof path.referral_type !== 'undefined' && path.referral_type !== "") { strHref += '&referral_type=' + "category"; } else { delete path.referral_type; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; */ // $rootScope.$on('$routeChangeStart', function(event, current, prev) { // if ($scope.dataProductStatus.done && $scope.dataProduct.length) { // $scope.dataProductStatus.done = false; // $scope.dataProduct = []; // } // }); // $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { // if (!$scope.dataProductStatus.done && !$scope.dataProduct.length) { // $timeout(function() { // $scope.getData(); // }, 100); // } // }); /* product/lists Update */ }; return promise; });_ui_share_app.directive('productGridTypeEy', function($rootScope, $routeParams) { var templateName = 'productGridTypeEy'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', sort : '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; if($scope.sort == undefined){ var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_sortby' : 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify(option) }; }else{ var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; } /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option, e); if (e.data.total_rows <= 0) { $scope.getReferal(ref_id); } }); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Fetch referral list */ $scope.referralArray = []; $scope.getReferal = function(ref_id) { var d = { txt_referral_type_id: 11, txt_parent_id: ref_id }; GAEAPI.get('referral/map', d).then(function(e) { $scope.referralArray = e.data; }); }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productGridTypeEz', function($rootScope, $routeParams) { var templateName = 'productGridTypeEz'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', sort : '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; if($scope.sort == undefined){ var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; }else{ var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; } /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option, e); if (e.data.total_rows <= 0) { $scope.getReferal(ref_id); } }); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* Fetch referral list */ $scope.referralArray = []; $scope.getReferal = function(ref_id) { var d = { txt_referral_type_id: 11, txt_parent_id: ref_id }; GAEAPI.get('referral/map', d).then(function(e) { $scope.referralArray = e.data; }); }; $scope.checkHide = function() { if (CUR_THEME.shop_id() == 536) { return true; } return false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; }); _ui_share_app.directive('productGridTypeF', function ($rootScope, $routeParams) { var templateName = 'productGridTypeF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option); }); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productGridTypeG', function ($rootScope, $routeParams) { var templateName = 'productGridTypeG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option); }); }; }; return promise; }); _ui_share_app.directive('productGridTypeK', function ($rootScope, $routeParams, $location) { var templateName = 'productGridTypeK'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { params:'=params', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ /*$scope.$watch('params', function (newValue, oldValue) { if (!newValue) return; });*/ /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = ""; $scope.productListSort = $routeParams.sort || ""; $scope.getProduct = function () { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; /* Check: Search */ if(typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== ""){ option.search = $scope._viewRouteParams().search; } /* Check: referral */ if(typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0){ option.referral_id_array = [$scope._viewRouteParams().referral_id]; } /* Check: badge */ if(typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != ""){ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit,function(i,k){ option.badge_id_array.push(i); }); } /* Check: sort by */ var sortBy = 'product_lastest_create'; if(typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != ""){ var r = $scope._viewRouteParams().sort; switch(r){ case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var dataSend = { 'cur_page': (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 20, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; $scope.buildPaginationParameter(e.data); } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get All", dataSend, option, e); }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function (data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function (total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel){ var otherParams = ''; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; } setTimeout(function () { $scope.productListSort=sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; window.location.href = "category-lists?sort=" + sortbyModel + otherParams; }, 300); }; $scope.buildFilterUrl = function(exceptionalKey){ var a = ''; angular.forEach($routeParams, function (item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("pageChangedSuccess", current); $scope.getProduct(); }); $scope.displayInt = function(i){ return parseInt(i) || false; }; $scope.printSelected = function(a){ if($routeParams.sort==a){ return " selected"; } return " "; }; $scope.displayChange = function(e){ return window.location.href="category-lists?page=1&per_page="+e; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productGridTypeM', function ($rootScope, $routeParams) { var templateName = 'productGridTypeM'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * params listener * @params (default) * @return function */ $scope.getProduct(); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productArray = []; $scope.getProduct = function () { /* Set loading state */ /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } }); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; }; return promise; }); _ui_share_app.directive('productGridTypeN', function ($rootScope, $routeParams) { var templateName = 'productGridTypeN'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option); }); }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); /* For ProductPageTypeO *//* for productPageTypeP */_ui_share_app.directive('productGridTypeQ', function($rootScope, $routeParams, $location) { var templateName = 'productGridTypeQ'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { params: '=params', imgpath: '@imgpath', callback: '@callback', badgearray: '@badgeid', btnstyle: '@btnstyle', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; console.log("btnstyle :", $scope.btnstyle); if ($scope.btnstyle == '' || $scope.btnstyle == undefined) { $scope.btnstyle = 'filled_button_round_small'; } $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.watchCallbackArray = function() { var r = []; for (var i = 0; i < 12; i++) { r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }], product_badge: [{ badge_id: 18 }], callback_array: true }); } return r; }; $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.productState = { load: false, done: false }; $scope.cur_page = 1; $scope.per_page = ""; $scope.productListSort = $scope._viewRouteParams().sort || ""; $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; /*$scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function(input) { $scope.filterSortData = input; $timeout(function() { $scope.pathChange(); }, 300); };*/ $scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.getProduct = function(search) { $scope.pagination_data = {}; $scope.productState = { load: true, done: false }; var option = {}; option.badge_id_array = [18]; if (typeof search !== 'undefined' && typeof search !== "") { option.search = search; } else { if (typeof $scope._viewRouteParams().root_id !== 'undefined' && typeof $scope._viewRouteParams().root_id != 0) { option.referral_id_array_in = [$scope._viewRouteParams().root_id]; } if (typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0) { option.referral_id_array = [$scope._viewRouteParams().referral_id]; } if (typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != "") { var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit, function(i, k) { option.badge_id_array.push(i); }); } else if ($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false) { if ($scope.badgeid.indexOf(',') == -1) { var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i, k) { var test = i.trim(); if (option.badge_id_array.indexOf(test) == -1) { option.badge_id_array.push(i.trim()); } }); } else { var test = $scope.badgeid.trim(); if (option.badge_id_array.indexOf(test) == -1) { option.badge_id_array.push($scope.badgeid.trim()); } } } } var sortBy = 'root_category_index_asc'; if (typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != "") { var r = $scope._viewRouteParams().sort; switch (r) { case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var dataSend = { 'cur_page': (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 20, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; console.log("dataSend zaap", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { if (e.data.dataList.length > 0) { $scope.productArray = e.data.dataList; $scope.buildPaginationParameter(e.data); } else { $scope.productArray = []; } console.log("productArray", $scope.productArray); if ($("#feature-product").hasClass('hide')) { $('#feature-product').removeClass('hide'); } } $scope.productState = { load: false, done: true }; }); }; $scope.getProduct(); $scope.pathChange = function() { var buildOtherReferral = function() {}; var path = { sendtag: $scope._viewRouteParams().sendtag, root_id: $scope._viewRouteParams().root_id, referral_id: $scope._viewRouteParams().referral_id, referral_name: $scope._viewRouteParams().referral_name, page: $scope._viewRouteParams().page, per_page: $scope._viewRouteParams().per_page, referral_type: 'category', sort: $scope.filterSortData, badge: $scope.filterbadge, referral_id_map: $scope.sendtagreferralid, }; var strHref = 'category-lists'; if (typeof path.sendtag !== 'undefined' && path.sendtag !== "") { strHref += '&sendtag=' + path.sendtag; } else { delete path.sendtag; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.page !== 'undefined' && path.page !== "") { strHref += '&page=' + path.page; } else { delete path.page; } if (typeof path.per_page !== 'undefined' && path.per_page !== "") { strHref += '&per_page=' + path.per_page; } else { delete path.per_page; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge; } else { delete path.badge; } if (typeof path.referral_id_map !== 'undefined' && path.referral_id_map !== "") { strHref += '&referral_id_map=' + path.referral_id_map; } else { delete path.referral_id_map; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.pagination_data = {}; $scope.buildPaginationParameter = function(data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function(total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; $location.path(pathStr).search(paramsObj); }, 300); }; $scope.displayChange = function(e) { if (window.location.href.indexOf('category-lists') !== -1) { $location.path("/category-lists").search({ 'page': 1, 'per_page': e }); } else { $location.path("/all-products").search({ 'page': 1, 'per_page': e });; } }; $scope.buildFilterUrl = function(exceptionalKey) { var a = ''; angular.forEach($routeParams, function(item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i) { return parseInt(i) || false; }; $scope.printSelected = function(a) { if ($routeParams.sort == a) { return " selected"; } return " "; }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { console.log("pageChangedSuccess", current); $scope.getProduct(); }); $scope.show_branch = ''; $scope.datamap = ''; $scope._page_branch = []; $scope._get_page_branch = function() { var dataSend = { 'cur_page': 1, 'per_page': 50, }; GAEAPI.get('shop_branch/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._page_branch = res.data.dataList; } }); }; $scope._get_page_branch(); $scope.popupOpen = function() { $('#datamap').attr('src', $("#data-dropdown").val()); $("#intro").addClass("active"); }; $scope.popupClose = function() { $("#intro").removeClass("active"); $scope.show_branch = $("#data-dropdown option:selected").text(); }; $('select').on('change', function() { /*alert(this.value);*/ $('#datamap').attr('src', $("#data-dropdown").val()); $scope.datamap = $scope.buildIframeMapByLoc($scope.datamap, 0, 0); }); $scope.buildIframeMapByLoc = function(name, lat, lng) { var newName = name; var DataName = name; if (/\s/.test(name)) { var newNameOld = name.split(" "); DataName = newNameOld.join("+"); } var srcByName = 'https://www.google.co.th/maps?q=' + DataName + '&output=embed&hl=th-TH'; var srcByLoc = 'https://www.google.co.th/maps?q=' + lat + ',' + lng + '&output=embed&hl=th-TH'; return (parseInt(lat) != 0 && parseInt(lng) != 0) ? srcByLoc : srcByName; }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $("input.input-search").keyup(function(event) { if (event.keyCode == 13) { $("#id_of_button").click(); } }); $scope.sale = function(price, compare_price, discount_id, discount_price, discount_percent) { if (discount_id != undefined) { return true; } else { return false; } } $scope._sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = discount_price; } else if (discount_percent != 0 && discount_price == 0) { sale = discount_percent; } } return (sale > 0) ? sale : 0; } $scope.__sale = function(price, compare_price, discount_id, discount_price, discount_percent) { var sale = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { sale = 'price'; } else if (discount_percent != 0 && discount_price == 0) { sale = 'percent'; } } return (sale != 0) ? sale : 0; } $scope.renderBadgeType = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'No Badge'; switch (r) { case 72: str = "เมนูใหม่"; break; case 74: str = "เมนูแนะนำ"; break; case 75: str = "เมนูขายดี"; break; case 16: str = "มังสวิรัติ"; break; default: str = "null"; break; } return str; }; $scope.renderBadgeClass = function(objectItem) { var r = parseInt(objectItem.badge_id); var str = 'NoBadge'; switch (r) { case 72: str = "NewArrival"; break; case 74: str = "Recommend"; break; case 75: str = "BestSeller"; break; case 16: str = "Featured"; break; default: str = "null"; break; } return str; }; }; return promise; });_ui_share_app.directive('productGridTypeR', function($rootScope, $routeParams, $location) { var templateName = 'productGridTypeR'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referralid_: '@referralid' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._Arrayproduct = []; $scope.DataArrayproductState = { load: true, done: false }; $scope._getDataproduct = function(input) { $scope.DataArrayproductState.load = true; $scope.DataArrayproductState.done = false; var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify({ "referral_id_array": [input] }) }; GAEAPI.get('product/lists', dataSend).then(function(res) { if (res.ok === 1) { $scope._Arrayproduct = res.data.dataList; } $scope.DataArrayproductState.load = false; $scope.DataArrayproductState.done = true; }); }; $scope._getDataproduct($scope.referralid_); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; }); _ui_share_app.directive('productGridTypeY', function ($rootScope, $routeParams) { var templateName = 'productGridTypeY'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referral: '=referral', referralname: '=referralname', limit: '@limit', name: '@name', imgpath: '@imgpath', imgcart : '@imgcart', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id) { if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': 1, 'per_page': $scope.limit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get", dataSend, option, e); if(e.data.total_rows <= 0){ $scope.getReferal(ref_id); } }); }; /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Fetch referral list */ $scope.referralArray = []; $scope.getReferal = function(ref_id){ var d = { txt_referral_type_id:11, txt_parent_id: ref_id }; GAEAPI.get('referral/map',d).then(function(e){ $scope.referralArray = e.data; }); }; $scope.checkHide = function(){ if(CUR_THEME.shop_id()==536){ return true; } return false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageByRefid', function($rootScope, $routeParams) { var templateName = 'productPageByRefid'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', refid: '=refid', col: '@col', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { console.log("Watch Referral", newValue); if (newValue != 0) { $scope.getProduct(newValue, false); $scope.getRefByid1(newValue); } else if (newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 50; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue, true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id, isPageChange) { $scope.fetchType = 0; $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': ref_id, 'txt_sortby': 'referral_sort_index_desc_time_asc', }; /* Fetch Data */ GAEAPI.get('referral/map', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data; $scope.productArray = (e.ok == 1) ? e.data : []; var temp_ttc = []; for (var i = 0; i < e.data.length; i++) { temp_ttc.push(e.data[i].referral_id); } ref_tcc_productArray = e.data; /* getproductForRef(0, function() { console.log("getproductForRef_ref : ref_tcc_productArray: ", ref_tcc_productArray); });*/ getproductForRef_last(0, function() { console.log("getproductForRef_ref_last : ref_tcc_productArray_last: ", ref_tcc_productArray); }); $scope.productArray = ref_tcc_productArray; } $scope.productState.load = false; $scope.productState.done = true; // console.log("Share Component Get: ref", dataSend, option); }); }; var ref_tcc_productArray = []; function getproductForRef(index, callback) { if (ref_tcc_productArray.length <= index) { if (callback) { callback(); } return; } var albumData = ref_tcc_productArray[index]; var image_group_id = albumData.referral_id; var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': image_group_id, 'txt_sortby': 'referral_oldest_create', }; console.log("referral/map : dataSend : ", dataSend); GAEAPI.get('referral/map', dataSend, $scope).then(function(res) { console.log("map/lists : res : ", res); if (res.ok == 1) { albumData.category_array = res.data; } ref_tcc_productArray_last = res.data; getproductForRef_last(0, function() { console.log("getproductForRef_ref_last : ref_tcc_productArray_last: ", ref_tcc_productArray_last); }); $scope.productArray = ref_tcc_productArray; console.log("getProduct getproductForRef : productArray : ", $scope.productArray); getproductForRef((index + 1), callback); }); } var ref_tcc_productArray_last = []; function getproductForRef_last(index, callback) { if (ref_tcc_productArray.length <= index) { if (callback) { callback(); } return; } var albumData_last = ref_tcc_productArray[index]; var image_group_last = albumData_last.referral_id; var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'product_oldest_create', 'txt_filter_json': JSON.stringify({ "referral_id_array_in": [image_group_last] }) }; console.log("product/lists : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(res) { console.log("image/lists : res : ", res); if (res.ok == 1) { albumData_last.product_array = res.data.dataList; } getproductForRef_last((index + 1), callback); }); } /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function(isPageChange) { if (isPageChange) { $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby': 'product_title_a-z', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); $('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75, 300], slide: function(event, ui) {} }); }); }; $scope.Refaray = []; $scope.getRefByid = function() { /* Begin Settingup Date */ var dataSend = { 'txt_referral_id': $scope.referral, }; /* Fetch Data */ GAEAPI.get('referral/id', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.Refaray = e.data; } $scope.getRefByid1(e.data.referral_parent_id); // console.log("Share Component Get: all", dataSend, option, Refaray); }); }; $scope.getRefByid(); $scope.Refaray1 = []; $scope.getRefByid1 = function(id_ref) { /* Begin Settingup Date */ var dataSend = { 'txt_referral_id': id_ref, }; /* Fetch Data */ GAEAPI.get('referral/id', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.Refaray1 = e.data; } // console.log("Share Component Get: all", dataSend, option, Refaray); }); }; $scope.loadMore = function() { $('div#slider-range').html(''); if ($scope.fetchType == 1) { $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function() { if ($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem) { var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if (ObjectItem.referral_parent_id != 0) { str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.setdispay = function(imgid) { document.getElementById(imgid).style.display = 'block'; $('body').css('overflow', 'hidden'); } $scope.setdispayclose = function(imgid) { document.getElementById(imgid).style.display = 'none'; $('body').css('overflow', 'visible'); } $scope.displayImage = function(image_url, prefix) { return GAEAPI.getGaeImageUrl(image_url, prefix); } $scope.$watch('col', function(newValue, oldValue) { if (!newValue) { return; } $scope._col = newValue.toString().split(","); }); $scope.getCol = function(n) { return (typeof $scope._col != 'undefined') ? (typeof $scope._col[n] != 'undefined' && $scope._col[n] != '') ? $scope._col[n] : 12 : 12; }; }; return promise; });_ui_share_app.directive('productPageTypeA', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', optimize: '@optimize', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.is_optimize = (typeof $scope.optimize !== 'undefined' && $scope.optimize !== "") ? true : false; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.routeParams = $routeParams; $scope._params = $routeParams.referral_type; $scope._params_id = $routeParams.root_id; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArray_Mobile = []; $scope.ReferralBrandArray = []; $scope.ReferralBrandArray_Mobile = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; for (var i = 0; i < $scope.ReferralDisplayArray.length; i++) { var item = $scope.ReferralDisplayArray[i]; item.root_id = 0; $scope.ReferralDisplayArray_Mobile.push(item); if (item.referral_sub_array.length > 0) { for (var ii = 0; ii < item.referral_sub_array.length; ii++) { item.referral_sub_array[ii].root_id = item.referral_id; $scope.ReferralDisplayArray_Mobile.push(item.referral_sub_array[ii]); } } } } /* console.log("test_page_mobile9",$scope.ReferralDisplayArray_Mobile); */ }); GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; for (var i = 0; i < $scope.ReferralBrandArray.length; i++) { var item = $scope.ReferralBrandArray[i]; item.root_id = 0; $scope.ReferralBrandArray_Mobile.push(item); if (item.referral_sub_array.length > 0) { for (var ii = 0; ii < item.referral_sub_array.length; ii++) { item.referral_sub_array[ii].root_id = item.referral_id; $scope.ReferralBrandArray_Mobile.push(item.referral_sub_array[ii]); } } } } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) { $scope.getProduct(); } else { $scope.getProduct(); } }); $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.productArray = []; $scope.JsonProductArrayState = { load: false, done: false }; $scope.isProductLoad = false; $scope.isNoProduct = false; $scope.getProduct = function() { $scope.isProductLoad = true; $scope.isNoProduct = false; var option = {}; option.badge_id_array = [18]; /* option.referral_id_array=[ref_id]; */ var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { $scope.isProductLoad = false; if (e.ok === 1) { $scope.productArray = e.data.dataList; if($scope.productArray.length <= 0){ $scope.isNoProduct = true; } $('[data-on="finish-load_all"]').hide(); /*if ($scope.productArray.length <= 0) { $('[data-on="finish-load"] span').text("ขออภัยไม่พบสินค้าที่เลือก 11111"); } else { $('[data-on="finish-load"] span').text("Loading please wait... 22222"); }*/ if ($scope._viewRouteParams().referral_type == 'categoryall' && $scope.productArray.length > 0) { $('[data-on="finish-load_all"]').hide(); $('[data-on="finish-data"]').show().css('opacity', '1'); } } $scope.JsonProductArrayState = $scope.StateData(false, true); }); }; $scope.getProduct(); $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope.viewOptimizeImage = function(size, image_url) { if (angular.isDefined($scope.is_optimize) && !$scope.is_optimize) { return image_url; } var a = image_url.split("/"); var b = a[a.length - 1]; a[a.length - 1] = 't' + size + '_' + b; return a.join("/"); }; $scope.ref_id_pd = false; $scope.load_ref_id = false; $scope.getProductId = function(value) { var dataSend = { 'txt_referral_id': value, }; /* Fetch Data */ GAEAPI.get('referral/id', dataSend, $scope).then(function(e) { $timeout(function() { $scope.load_ref_id = true; }, 5000); if (e.ok === 1) { $scope.ref_id_pd = e.data; } }); }; /* Select menu for mobile */ $scope.shopByCategoryModel = ''; $scope.shopByCategoryModelDisplay = 'Choose'; $scope.shopByCategoryModelDoChange = function(newValue) { var arraySring = newValue.split(","); var name = arraySring[2]; if (arraySring[0] != '0') { var parentId = arraySring[0]; } else { var parentId = arraySring[1]; } var referralId = arraySring[1]; $scope.shopByCategoryModelDisplay = name; var params = { 'root_id': parentId, 'referral_id': referralId, 'referral_type': 'category' }; $timeout(function() { $location.path('/category-lists').search(params); }, 300); console.log("test_page_mobile3", $scope.routeParams); console.log("test_page_mobile2", arraySring); console.log("test_page_mobile", params); }; /* Select menu for mobile */ $scope.shopByBrandModel = ''; $scope.shopByBrandModelDisplay = 'Choose'; $scope.shopByBrandModelDoChange = function(newValue) { var arraySring = newValue.split(","); var name = arraySring[2]; var parentId = arraySring[0]; var referralId = arraySring[1]; $scope.shopByBrandModelDisplay = name; var params = { 'root_id': parentId, 'referral_id': referralId, 'referral_type': 'brand' }; $timeout(function() { $location.path('/category-lists').search(params); }, 300); }; }; return promise; }); _ui_share_app.directive('productPageTypeB', function ($rootScope, $routeParams) { var templateName = 'productPageTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeBs', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeBs'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', home: '@home', category: '@category', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeBs : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.state = ""; $scope.cover_top = ($scope.category != undefined && $scope.category != "") ? $scope.category : "category-lists"; $scope.totalRows = 0; $scope.totalRowsState = $scope.getData().stateData(false, false); $scope.dataRelation = []; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.getData().consoleLog('referral/id : res : ', output); $scope.cover_top = output.data.referral_name; }); }); var txt_filter_json = {}; var dataSend = { 'txt_referral_id': params.referral_id, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('referral/id_map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.totalRows = output.data.referral_product_amount; $scope.totalRowsState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; $scope.totalRowsState = $scope.getData().stateData(false, true); }); }); var txt_filter_json = {}; var dataSend = { 'txt_referral_id': params.referral_id, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('referral/id_map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.totalRows = output.data.referral_product_amount; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.state = ""; $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData, price: $scope.price }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; }; return promise; }); _ui_share_app.directive('productPageTypeC', function ($rootScope, $routeParams) { var templateName = 'productPageTypeC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', btntext: '@btntext', imgcart: '@imgcart', lang: '@lang', btnaddpdtext: '@btnaddpdtext', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.shop_id = CUR_THEME.shop_id(); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeCBadge', function ($rootScope, $routeParams) { var templateName = 'productPageTypeCBadge'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', btntext: '@btntext', imgcart: '@imgcart', lang: '@lang', btnaddpdtext: '@btnaddpdtext', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.shop_id = CUR_THEME.shop_id(); /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeCa', function ($rootScope, $routeParams) { var templateName = 'productPageTypeCa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', btntext: '@btntext', imgcart: '@imgcart', lang: '@lang', btnaddpdtext: '@btnaddpdtext', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.shop_id = CUR_THEME.shop_id(); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeCb', function ($rootScope, $routeParams, $location) { var templateName = 'productPageTypeCb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', imgcart: '@imgcart', btnaddpdtext: '@btnaddpdtext', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope._params = $routeParams.referral_id; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArray_Mobile = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; for (var i = 0; i < $scope.ReferralDisplayArray.length; i++) { var item = $scope.ReferralDisplayArray[i]; item.root_id = 0; $scope.ReferralDisplayArray_Mobile.push(item); if (item.referral_sub_array.length > 0) { for (var ii = 0; ii < item.referral_sub_array.length; ii++) { item.referral_sub_array[ii].root_id = item.referral_id; $scope.ReferralDisplayArray_Mobile.push(item.referral_sub_array[ii]); } } } } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if(newValue){ $scope._get_referral_relate_(newValue); } if (!newValue) return; }); $scope._data_referral_relate_ = []; $scope._get_referral_relate_ = function (array) { var dataSend = { 'txt_referral_id': array, }; GAEAPI.get('referral/relation', dataSend).then(function (e) { if (e.ok === 1) { $scope._data_referral_relate_ = e.data; } }); }; /* Select menu for mobile */ $scope.shopByCategoryModel = ''; $scope.shopByCategoryModelDisplay = 'Choose'; $scope.shopByCategoryModelDoChange = function(newValue) { var arraySring = newValue.split(","); var name = arraySring[2]; if (arraySring[0] != '0') { var parentId = arraySring[0]; } else { var parentId = arraySring[1]; } var referralId = arraySring[1]; $scope.shopByCategoryModelDisplay = name; var params = { 'parent_id': parentId, 'referral_id': referralId, 'referral_type': 'category' }; $timeout(function() { $location.path('/product-category').search(params); }, 300); console.log("test_page_mobile3", $scope.routeParams); console.log("test_page_mobile2", arraySring); console.log("test_page_mobile", params); }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeCc', function ($rootScope, $routeParams, $location) { var templateName = 'productPageTypeCc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', imgcart: '@imgcart', btnaddpdtext: '@btnaddpdtext', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope._params = $routeParams.referral_id; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArray_Mobile = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; for (var i = 0; i < $scope.ReferralDisplayArray.length; i++) { var item = $scope.ReferralDisplayArray[i]; item.root_id = 0; $scope.ReferralDisplayArray_Mobile.push(item); if (item.referral_sub_array.length > 0) { for (var ii = 0; ii < item.referral_sub_array.length; ii++) { item.referral_sub_array[ii].root_id = item.referral_id; $scope.ReferralDisplayArray_Mobile.push(item.referral_sub_array[ii]); } } } } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if(newValue){ $scope._get_referral_relate_(newValue); } if (!newValue) return; }); $scope._data_referral_relate_ = []; $scope._get_referral_relate_ = function (array) { var dataSend = { 'txt_referral_id': array, }; GAEAPI.get('referral/relation', dataSend).then(function (e) { if (e.ok === 1) { $scope._data_referral_relate_ = e.data; } }); }; /* Select menu for mobile */ $scope.shopByCategoryModel = ''; $scope.shopByCategoryModelDisplay = 'Choose'; $scope.shopByCategoryModelDoChange = function(newValue) { var arraySring = newValue.split(","); var name = arraySring[2]; if (arraySring[0] != '0') { var parentId = arraySring[0]; } else { var parentId = arraySring[1]; } var referralId = arraySring[1]; $scope.shopByCategoryModelDisplay = name; var params = { 'parent_id': parentId, 'referral_id': referralId, 'referral_type': 'category' }; $timeout(function() { $location.path('/product-category').search(params); }, 300); console.log("test_page_mobile3", $scope.routeParams); console.log("test_page_mobile2", arraySring); console.log("test_page_mobile", params); }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeCe', function ($rootScope, $routeParams) { var templateName = 'productPageTypeCe'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._viewRouteParams = function () { return $routeParams || false; }; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope._params = $scope._viewRouteParams().referral_id || false; console.log("sdssdsdsdssds :",$scope._params); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope.support_data = { category: [], }; $scope._getSupportDataCategory = function(type,data){ var dataSend = { 'txt_referral_id': data }; GAEAPI.get('referral/relation',dataSend).then(function(e){ if(e.ok == 1){ $scope.support_data.category = e.data; } }); }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if(newValue){ $scope._getSupportDataCategory('category', newValue); } if (!newValue) return; }); $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeD', function ($rootScope, $routeParams) { var templateName = 'productPageTypeD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', datafont: '@datafont', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window ,$location ,$http) { $scope._params = $routeParams.referral_id; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby':'referral_sort_index_asc_name_asc' }; if($scope._params != undefined){ d.txt_parent_id = $scope._params; console.log("sodisojsjskj :", d); } var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } console.log("referral display", e.data); }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplayArrayId = []; $scope.FetchDisplayCategoryId = function () { $scope.ReferralDisplayArrayId = []; var d = { 'txt_referral_id': $scope._params, }; GAEAPI.get('referral/id', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArrayId = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } if ($scope._params != undefined) { $scope.FetchDisplayCategoryId(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); }; return promise; }); _ui_share_app.directive('productPageTypeE', function($rootScope, $routeParams) { var templateName = 'productPageTypeE'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading_:'@heading', childcomponent: '@childcomponent', imgpath: '@imgpath', imgcart: '@imgcart' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeEa', function($rootScope, $routeParams) { var templateName = 'productPageTypeEa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading_:'@heading', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeEb', function($rootScope, $routeParams) { var templateName = 'productPageTypeEb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading_:'@heading', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope._params = $routeParams.referral_id; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.support_data = []; /* get other data */ $scope._getSupportDataCategory = function(data_number){ var dataSend = { 'txt_referral_id': data_number }; GAEAPI.get('referral/relation',dataSend).then(function(e){ console.log("_getSupportDataCategory", dataSend, e); if(e.ok == 1){ $scope.support_data = e.data; } }); }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue){ return; } if(newValue){ $scope._getSupportDataCategory(newValue); } }); /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productPageTypeEc', function($rootScope, $routeParams) { var templateName = 'productPageTypeEc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading_:'@heading', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope._params = $routeParams.referral_id; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if(newValue){ $scope._get_referral_relate_(newValue); } if (!newValue) return; }); $scope._data_referral_relate_ = []; $scope._get_referral_relate_ = function (array) { var dataSend = { 'txt_referral_id': array, }; GAEAPI.get('referral/relation', dataSend).then(function (e) { if (e.ok === 1) { $scope._data_referral_relate_ = e.data; } }); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeEd', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeEd'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading_: '@heading', childcomponent: '@childcomponent', imgpath: '@imgpath', carouselheight: '@carouselheight', magin: '@magin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewType = 'grid'; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope._params = $routeParams.referral_id; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (newValue) { $scope._get_referral_relate_(newValue); } if (!newValue) return; }); $scope.productListSort = $scope._viewRouteParams().sort || "product_lifetime_start_asc"; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/category-lists'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { otherParams += "&referral_type=" + 'category'; paramsObj.referral_type = 'category'; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $location.path(pathStr).search(paramsObj); }, 300); }; $scope._data_referral_relate_ = []; $scope._get_referral_relate_ = function(array) { var dataSend = { 'txt_referral_id': array, }; GAEAPI.get('referral/relation', dataSend).then(function(e) { if (e.ok === 1) { $scope._data_referral_relate_ = e.data; } }); }; $scope.mkCarousel = function(elem) { $('.product-page-type-ed .recommend').css('height', '0'); $('.product-page-type-ed .recommend').css('opacity', '0'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 992, settings: { slidesToShow: 1 } }, { breakpoint: 768, settings: { slidesToShow: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1 } }] }).closest('section').addClass('active'); $('.product-page-type-ed .recommend').css('opacity', '1'); $('.product-page-type-ed .recommend').css('height', 'auto'); }, 100); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeEe', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeEe'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading_: '@heading', childcomponent: '@childcomponent', imgpath: '@imgpath', carouselheight: '@carouselheight', magin: '@magin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewType = 'grid'; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope._params = $routeParams.referral_id; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); $scope.FetchDisplayCategory(); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (newValue) { $scope._get_referral_relate_(newValue); } if (!newValue) return; }); $scope.productListSort = $scope._viewRouteParams().sort || "product_lifetime_start_asc"; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/category-lists'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { otherParams += "&referral_type=" + 'category'; paramsObj.referral_type = 'category'; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $location.path(pathStr).search(paramsObj); }, 300); }; $scope._data_referral_relate_ = []; $scope._get_referral_relate_ = function(array) { var dataSend = { 'txt_referral_id': array, }; GAEAPI.get('referral/relation', dataSend).then(function(e) { if (e.ok === 1) { $scope._data_referral_relate_ = e.data; } }); }; $scope.mkCarousel = function(elem) { $('.product-page-type-ed .recommend').css('height', '0'); $('.product-page-type-ed .recommend').css('opacity', '0'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 992, settings: { slidesToShow: 1 } }, { breakpoint: 768, settings: { slidesToShow: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1 } }] }).closest('section').addClass('active'); $('.product-page-type-ed .recommend').css('opacity', '1'); $('.product-page-type-ed .recommend').css('height', 'auto'); }, 100); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeEf', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeEf'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading_:'@heading', childcomponent: '@childcomponent', imgpath: '@imgpath', params: '@params', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; // setTimeout(function() { $scope._params = $routeParams.referral_id; // }, 100); // alert($scope._params); /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ // $scope._params = $routeParams.referral_id; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("ReferralDisplaylistsArray : 03 :", $routeParams.referral_id, $scope.ReferralDisplayArray); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray : 01 :", $routeParams.referral_id, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray : 02 :", $routeParams.referral_id, $scope.NameDisplaylistsArray); }); }; // if ($routeParams.referral_id != 'undefined') { // $scope.FetchDisplayCategorylists($routeParams.referral_id); // $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); // } // if (!$scope.ReferralDisplayArray.length) { // $scope.FetchDisplayCategory(); // } /* * view current routeParams * @params (default) * @return function */ $scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function(data) { $scope.filterSortData = data; // alert($scope.filterSortData); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.pathChange = function() { var buildOtherReferral = function() {}; var path = { referral_id: $scope._viewRouteParams().referral_id, root_id: $scope._viewRouteParams().root_id, referral_type: $scope._viewRouteParams().referral_type, sort: $scope.filterSortData }; var strHref = 'category-lists'; if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '?referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '&root_id=' + path.root_id; } else { delete path.root_id; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.referral_type !== 'undefined' && path.referral_type !== "") { strHref += '&referral_type=' + path.referral_type; } else { delete path.referral_type; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; /* * params listener * @params (default) * @return function */ $scope.$watch('params', function(newValue, oldValue) { if(newValue){ // alert(newValue); $scope._get_referral_relate_(newValue); $scope.FetchDisplayNameDisplaylistsArray(newValue); $scope.FetchDisplayCategorylists(newValue); $scope.FetchDisplayCategory(); // alert(newValue); } else{ $scope.FetchDisplayCategory(); if($scope._params == undefined){ // alert("sdsdsd"); // $scope.FetchDisplayCategory(); }else{ // alert("aa"+$scope._params); } // $scope._get_referral_relate_(newValue); // $scope.FetchDisplayNameDisplaylistsArray(newValue); // $scope.FetchDisplayCategorylists(newValue); } }); $scope._data_referral_relate_ = []; $scope._get_referral_relate_ = function (array) { var dataSend = { 'txt_referral_id': array, }; GAEAPI.get('referral/relation', dataSend).then(function (e) { if (e.ok === 1) { $scope._data_referral_relate_ = e.data; } }); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeEg', function($rootScope, $routeParams) { var templateName = 'productPageTypeEg'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading_:'@heading', childcomponent: '@childcomponent', imgpath: '@imgpath', imgcart: '@imgcart' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray , e.data.length); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.getRelation($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; }); _ui_share_app.directive('productPageTypeF', function ($rootScope, $routeParams) { var templateName = 'productPageTypeF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } console.log("referral display", e.data); }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeG', function($rootScope, $routeParams) { var templateName = 'productPageTypeG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; console.log("Share Component Get: all", e.data); } }); GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; console.log("Share Component Get: all1", e.data); } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } $scope.RefById = []; $scope.RefByCategory = function() { $scope.RefById = []; var d = { 'txt_referral_id': $scope.referral }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.RefById = e.data; console.log("Share Component Get: Ref", e.data); } else { $scope.RefById.referral_name = ""; } }); }; if ($scope.referral) { $scope.RefByCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (newValue != 0) { $scope.getProduct(newValue); } else if (newValue == 0 || !newValue) { $scope.getAllProduct(); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 9; /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.end_loadmore = false; $scope.getProduct = function(ref_id) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': ($scope.fetchTimes > 1) ? $scope.fetchLimit : $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option, $scope.fetchTimes, $scope.end_loadmore); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function() { $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': ($scope.fetchTimes > 1) ? $scope.fetchLimit : $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option, $scope.fetchTimes); }); }; $scope.loadMore = function() { if ($scope.fetchType == 1) { $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* CHeck If Seo SIte */ $scope.checkSeoLink = function(productId) { return (GURL.isHtml5Mode()) ? 'product-detail/' + productId : '#/product-detail/' + productId; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productPageTypeGb', function($rootScope, $routeParams) { var templateName = 'productPageTypeGb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; console.log("Share Component Get: all", e.data); } }); GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; console.log("Share Component Get: all1", e.data); } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } $scope.RefById = []; $scope.RefByCategory = function() { $scope.RefById = []; var d = { 'txt_referral_id': $scope.referral }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.RefById = e.data; console.log("Share Component Get: Ref", e.data); } else { $scope.RefById.referral_name = ""; } }); }; if ($scope.referral) { $scope.RefByCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (newValue != 0) { $scope.getProduct(newValue); } else if (newValue == 0 || !newValue) { $scope.getAllProduct(); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 9; /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.end_loadmore = false; $scope.getProduct = function(ref_id) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': ($scope.fetchTimes > 1) ? $scope.fetchLimit : $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option, $scope.fetchTimes, $scope.end_loadmore); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function() { $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': ($scope.fetchTimes > 1) ? $scope.fetchLimit : $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option, $scope.fetchTimes); }); }; $scope.loadMore = function() { if ($scope.fetchType == 1) { $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* CHeck If Seo SIte */ $scope.checkSeoLink = function(productId) { return (GURL.isHtml5Mode()) ? 'product-detail/' + productId : '#/product-detail/' + productId; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productPageTypeGc', function($rootScope, $routeParams) { var templateName = 'productPageTypeGc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; console.log("Share Component Get: all", e.data); } }); GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; console.log("Share Component Get: all1", e.data); } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } $scope.RefById = []; $scope.RefByCategory = function() { $scope.RefById = []; var d = { 'txt_referral_id': $scope.referral }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.RefById = e.data; console.log("Share Component Get: Ref", e.data); } else { $scope.RefById.referral_name = ""; } }); }; if ($scope.referral != undefined || $scope.referral != '') { $scope.RefByCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { if (newValue != 0) { $scope.getProduct(newValue); } else if (newValue == 0 || !newValue) { $scope.getAllProduct(); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 9; /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.end_loadmore = false; $scope.getProduct = function(ref_id) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': ($scope.fetchTimes > 1) ? $scope.fetchLimit : $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option, $scope.fetchTimes, $scope.end_loadmore); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function() { $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': ($scope.fetchTimes > 1) ? $scope.fetchLimit : $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.end_loadmore = true; } else { $scope.end_loadmore = false; } } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option, $scope.fetchTimes); }); }; $scope.loadMore = function() { if ($scope.fetchType == 1) { $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* CHeck If Seo SIte */ $scope.checkSeoLink = function(productId) { return (GURL.isHtml5Mode()) ? 'product-detail/' + productId : '#/product-detail/' + productId; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productPageTypeGe', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeGe'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { menu: '@menu', home: '@home', text: '@text', cardgrid: '@cardgrid', cardlist: '@cardlist', styletextgrid: '@styletextgrid', stylebuttongrid: '@stylebuttongrid', imgcartgrid: '@imgcartgrid', styletextlist: '@styletextlist', stylebuttonlist: '@stylebuttonlist', imgcartlist: '@imgcartlist', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._home = ($scope.home != undefined && $scope.home != "") ? $scope.home : "หน้าแรก"; $scope.returnJson = function(data, callback) { var json = JSON.parse(data); callback(json); }; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeObb : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = $scope.text; $scope.sub_products = "0"; $scope.state = ""; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArrayMain = []; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { console.log('referral/id : output : ', output); $scope.cover_top = output.data.referral_name; if (output.data.referral_image.length != 0) { $scope.cover_background_image_top = output.data.referral_image[0].image_url; } }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.sub_products = params.referral_id; if (output.data == 0) { $scope.state = "sub_category_products"; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.cover_background_image_top = ""; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "NEW PRODUCT"; } else if (params.badge_id == "74") { $scope.cover_top = "BEST SELLER"; } else if (params.badge_id == "75") { $scope.cover_top = "RECOMMEND"; } $scope.cover_background_image_top = ""; $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_lastest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData, price: $scope.price }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; $scope.price = { min: 0, max: 9999999 }; $scope.setPrice = function() { console.log("setPrice : price : ", $scope.price); }; }; return promise; }); _ui_share_app.directive('productPageTypeH', function ($rootScope, $routeParams) { var templateName = 'productPageTypeH'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { if (newValue != 0) { $scope.getProduct(newValue); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function () { $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); $('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} }); }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeHub', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeHub'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', home: '@home', category: '@category', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.home = (typeof $scope.home == undefined && $scope.home == '') ? "หน้าแรก" : $scope.home; $scope.category = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.cover_top = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.sub_products = "0"; $scope.state = ""; $scope.dataArray6113 = []; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; if (output.data == 0) { $scope.state = "sub_category_products"; $scope.sub_products = params.referral_id; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.sub_products = params.sendtag; var dataSend = { 'txt_referral_id': 6113 }; $scope.getData().dataSend('referral/id_map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray6113 = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "สินค้าใหม่"; } else if (params.badge_id == "74") { $scope.cover_top = "สินค้าขายดี"; } else if (params.badge_id == "75") { $scope.cover_top = "สินค้าแนะนำ"; } $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().badge || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; }; return promise; }); _ui_share_app.directive('productPageTypeI', function ($rootScope, $routeParams) { var templateName = 'productPageTypeI'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', refid: '=refid', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); $('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} }); }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeIb', function ($rootScope, $routeParams) { var templateName = 'productPageTypeIb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', refid: '@refid', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.loadMoreAll = false; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } if(e.data.total_rows <= $scope.productArray.length){ $scope.loadMoreAll = true; } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } if(e.data.total_rows <= $scope.productArray.length){ $scope.loadMoreAll = true; } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); // $('div#slider-range').slider({ // range: true, // min: 0, // max: 100, // values: [75,300], // slide: function(event, ui ) {} // }); }); }; $scope.loadMore = function(){ // $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = 'category-lists' + '?referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || 'home'; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeIc', function ($rootScope, $routeParams) { var templateName = 'productPageTypeIc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', refid: '@refid', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window ,$location) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope._viewRouteParams().referral_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; console.log("getDataCategoryParent : get :" , $scope.data_category_parent); }); }; $scope.getDataCategoryParent(); $scope.$watch('_params', function (newValue, oldValue) { if (!newValue){ return; } }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterCat = $scope._viewRouteParams().referral_id || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.loadMoreAll = false; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } if(e.data.total_rows <= $scope.productArray.length){ $scope.loadMoreAll = true; } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } if(e.data.total_rows <= $scope.productArray.length){ $scope.loadMoreAll = true; } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); $('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} }); }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = 'category-lists' + '?referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || 'home'; }; $scope.pathChange = function() { var path = { root_id: $scope._viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope._viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope._viewRouteParams().referral_name, /* view of this view */ sort: $scope.filterSortData, /* sortby */ }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } // if (typeof path.perpage !== 'undefined' && path.perpage !== "") { // strHref += '&perpage=' + path.perpage; // } else { // delete path.perpage; // } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeId', function ($rootScope, $routeParams) { var templateName = 'productPageTypeId'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', refid: '@refid', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window ,$location) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope._viewRouteParams().referral_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; console.log("getDataCategoryParent : get :" , $scope.data_category_parent); }); }; $scope.getDataCategoryParent(); $scope.$watch('_params', function (newValue, oldValue) { if (!newValue){ return; } }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterCat = $scope._viewRouteParams().referral_id || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 30; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.loadMoreAll = false; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } if(e.data.total_rows <= $scope.productArray.length){ $scope.loadMoreAll = true; } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } if(e.data.total_rows <= $scope.productArray.length){ $scope.loadMoreAll = true; } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); $('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} }); }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = 'category-lists' + '?referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || 'home'; }; $scope.pathChange = function() { var path = { root_id: $scope._viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope._viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope._viewRouteParams().referral_name, /* view of this view */ sort: $scope.filterSortData, /* sortby */ }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } // if (typeof path.perpage !== 'undefined' && path.perpage !== "") { // strHref += '&perpage=' + path.perpage; // } else { // delete path.perpage; // } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeJ', function ($rootScope, $routeParams) { var templateName = 'productPageTypeJ'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * fetch referral for menu (left side) * @params referral_id * @return {Array} */ $scope.ReferralMenuArray = []; $scope.FetchReferralMenuArray = function (ref_id) { $scope.ReferralMenuArray = []; var d = {'txt_referral_type_id': 11,'txt_parent_id':ref_id, 'txt_sortby':'referral_sort_index_asc_name_asc'}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralMenuArray = e.data; } }); }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); $scope.FetchReferralMenuArray($routeParams.root_id); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); $scope.FetchReferralMenuArray($routeParams.root_id); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Other Relate Data */ $scope.FetchRelationNav(ref_id); /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); /* Apply JQ */ $('div#range-input-1').html(''); $('div#range-input-1').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); $('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} }); }); /* Apply JQ */ $('div#range-input-1').html(''); $('div#range-input-1').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} }); }; /* Button to load more */ $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* String Enc */ $scope.strEncode = function(rawStr){ var encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/gim, function(i) { return '&#'+i.charCodeAt(0)+';'; }); return encodedStr; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem, customRootId){ var str = '#/product-template?id=10' + '&referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + $scope.strEncode(ObjectItem.referral_name); return str || '#/home'; }; /* Click to toggle child category */ $scope.toggleChild = function(id){ $('[data-id="sub-of-'+id+'"]').toggle(); }; $scope.RelationNavArray = []; $scope.FetchRelationNav = function(id){ $scope.RelationNavArray = []; GAEAPI.get('referral/relation',{'txt_referral_id':id,'txt_is_lookup':0},$scope).then(function(e){ if(e.ok == 1){ $scope.RelationNavArray = e.data; } }); }; /* Filter Toggle */ $scope.toggleFilter_First = 0; $scope.toggleFilter_Second = 0; $scope.toggleFilter_Third = 0; $scope.toggleFilter = function(i){ if(i == 1){ $scope.toggleFilter_First = ($scope.toggleFilter_First == 0) ? 1 : 0; } if(i == 2){ $scope.toggleFilter_Second = ($scope.toggleFilter_Second == 0) ? 1 : 0; } if(i == 3){ $scope.toggleFilter_Third = ($scope.toggleFilter_Third == 0) ? 1 : 0; } }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeK', function ($rootScope, $routeParams) { var templateName = 'productPageTypeK'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeKh', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeKh'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { menu: '@menu', text: '@text', cardgrid: '@cardgrid', cardlist: '@cardlist', styletextgrid: '@styletextgrid', stylebuttongrid: '@stylebuttongrid', imgcartgrid: '@imgcartgrid', styletextlist: '@styletextlist', stylebuttonlist: '@stylebuttonlist', imgcartlist: '@imgcartlist', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.returnJson = function(data, callback) { var json = JSON.parse(data); callback(json); }; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeObb : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = $scope.text; $scope.sub_products = "0"; $scope.state = ""; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArrayMain = []; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { console.log('referral/id : output : ', output); $scope.cover_top = output.data.referral_name; if (output.data.referral_image.length != 0) { $scope.cover_background_image_top = output.data.referral_image[0].image_url; } }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.sub_products = params.referral_id; if (output.data == 0) { $scope.state = "sub_category_products"; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.cover_background_image_top = ""; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "NEW PRODUCT"; } else if (params.badge_id == "74") { $scope.cover_top = "BEST SELLER"; } else if (params.badge_id == "75") { $scope.cover_top = "RECOMMEND"; } $scope.cover_background_image_top = ""; $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_lastest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData, price: $scope.price }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; $scope.price = { min: 0, max: 9999999 }; $scope.setPrice = function() { console.log("setPrice : price : ", $scope.price); }; }; return promise; }); _ui_share_app.directive('productPageTypeL', function ($rootScope, $routeParams) { var templateName = 'productPageTypeL'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.ref_id = $routeParams.referral_id; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.FetchDisplayCategory = function (ref_id) { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; if(typeof ref_id !== 'undefined'){ d.txt_parent_id = ref_id; } GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } console.log("referral display", d, e.data, ref_id); }); }; /*if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); }*/ /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('ref_id', function (newValue, oldValue) { if (!newValue || newValue == 0){ return $scope.FetchDisplayCategory(); } $scope.FetchDisplayCategory(newValue); }); /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; /* Check if child array exist */ $scope.checkChild = function(object){ return (!object.referral_sub_array.length) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeM', function($rootScope, $routeParams) { var templateName = 'productPageTypeM'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', margin: '@margin', heading_: '@heading', childcomponent: '@childcomponent', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState = $scope.StateData(true, false); $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState = $scope.StateData(false, true); console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState = $scope.StateData(true, false); $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState = $scope.StateData(false, true); console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState = $scope.StateData(true, false); $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState = $scope.StateData(false, true); console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeMaeju', function($rootScope, $routeParams) { var templateName = 'productPageTypeMaeju'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { stylebutton: '@stylebutton', component: '@component', viewdata: '@viewdata', name: '@name', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeMaeju : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 15, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; }); _ui_share_app.directive('productPageTypeMf', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productPageTypeMf'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', badgeid: '@badgeid', text: '@text', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval) { /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.data = []; $scope.data_done = false; /* Get data * @params id = badge id * @return array */ $scope.getData = function(id){ $scope.data = []; $scope.data_done = false; var d = { 'cur_page':1, 'per_page':8, 'txt_sortby':'product_lastest_create', 'txt_filter_json': JSON.stringify({'badge_id_array':[18,id]}) }; GAEAPI.get('product/lists',d,$scope).then(function(e){ if(e.ok == 1){ $scope.data = e.data.dataList; $scope.data_done = true; } }); }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('badgeid', function (newValue, oldValue) { if (!newValue){ return; } $scope.getData(newValue); }); /* Make Carousel */ $scope._makeProductToCarousel = function () { var elementName = '[data-id="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 4, slidesToScroll: 4, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, responsive: [ { breakpoint: 1170, settings: { slidesToShow: 3, slidesToScroll: 3, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false } } ] }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(){ return "-" + (($('.row.slick-slider[data-id="'+$scope._uniqueKey+'"]').height() / 2) + 34) + "px"; }; /* Carousel Arrow Click */ $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; /* Carousel Arrow Click */ $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { $timeout(function(){ $scope._makeProductToCarousel(); }, 500); }); /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; }); _ui_share_app.directive('productPageTypeMi', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productPageTypeMi'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval) { $scope.dataFeature = []; $scope.getReferralFeature = function(){ $scope.dataFeature = []; var d = { 'txt_referral_type_id':11, 'cur_page':1, 'per_page':10, 'txt_filter_json': JSON.stringify({'badge_id_array':[16]}) }; GAEAPI.get('referral/lists',d).then(function(res){ $scope.dataFeature = res.data.dataList; }); }; if(!$scope.dataFeature.length){ $scope.getReferralFeature(); } }; return promise; }); _ui_share_app.directive('productPageTypeMs', function ($rootScope, $routeParams, sliderProvider) { var templateName = 'productPageTypeMs'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', referralid: '@referralid', text: '@text', feature:'@feature', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval) { /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.data = []; $scope.data_done = false; $scope.data_brand = []; /* Get data * @params id = badge id * @return array */ $scope.getData = function(id){ $scope.data = []; $scope.data_done = false; var useFeature = ($scope.feature==true||$scope.feature==1) ? true : false; var filterJson = {'badge_id_array':[18],'referral_id_array':[id]}; if(useFeature){ filterJson.badge_id_array.push(16); } var d = { 'cur_page':1, 'per_page':8, 'txt_sortby':'product_lastest_create', 'txt_filter_json': JSON.stringify(filterJson) }; GAEAPI.get('product/lists',d,$scope).then(function(e){ if(e.ok == 1){ $scope.data = e.data.dataList; $scope.data_done = true; console.log("data_brand",$scope.data); var testArray = []; var dummyArray = []; angular.forEach(e.data.dataList,function(i,k){ if(typeof i.product_referral_display.brand !== 'undefined' && i.product_referral_display.brand.length){ var b = i.product_referral_display.brand[0].referral_name; if(testArray.indexOf(b)==-1){ testArray.push(b); dummyArray.push(i.product_referral_display.brand[0]); } } }); $scope.data_brand = dummyArray; console.log("data_brand",$scope.data_brand); } }); }; $scope.data_referral = []; $scope.data_referral_done = false; /* Get referral data by referral_id * @params id = referral id * @return array */ $scope.getDataReferral = function(id){ $scope.data = []; $scope.data_done = false; var d = { 'txt_referral_id':id }; GAEAPI.get('referral/id',d,$scope).then(function(e){ if(e.ok == 1){ $scope.data_referral = [e.data]; $scope.data_referral_done = true; } }); }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('referralid', function (newValue, oldValue) { if (!newValue){ return; } $scope.getData(newValue); $scope.getDataReferral(newValue); }); /* Make Carousel */ $scope._makeProductToCarousel = function () { var elementName = '[data-id="' + $scope._uniqueKey + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 4, slidesToScroll: 4, dots: false, arrows: false, centerMode: false, infinite: true, variableWidth: false, responsive: [ { breakpoint: 1170, settings: { slidesToShow: 3, slidesToScroll: 3, variableWidth: false, centerMode: false } }, { breakpoint: 769, settings: { slidesToShow: 2, slidesToScroll: 2, variableWidth: false, centerMode: false } }, { breakpoint: 601, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false } }, { breakpoint: 481, settings: { slidesToShow: 1, slidesToScroll: 1, variableWidth: false, centerMode: false, dots: false } } ] }; return sliderProvider(elementName, optionsParmas, $scope.type, $scope._uniqueKey); }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(){ return "-" + (($('.row.slick-slider[data-id="'+$scope._uniqueKey+'"]').height() / 2) + 34) + "px"; }; /* Carousel Arrow Click */ $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; /* Carousel Arrow Click */ $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { $timeout(function(){ }, 500); }); /* Check if seo enable */ $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; }); _ui_share_app.directive('productPageTypeNa', function ($rootScope, $routeParams) { var templateName = 'productPageTypeNa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', featured: '@featured', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval) { $scope.data_product = []; $scope.data = []; $scope.data_done = false; $scope.product_length = 0; /* Get data * @params badgeId = badge id * @return array */ /* UNIQUE KEY */ $scope._uniqueKey = ''; $scope._key = function () { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.getData = function (referralId, badgeId) { $scope.data_done = false; var filterJson = {'badge_id_array_for_root': [16]}; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_name_a-z', 'txt_filter_json': JSON.stringify(filterJson) }; GAEAPI.get('referral/map', d).then(function (e) { console.log("getProduct IN Ref : e :", e); if (e.ok == 1) { $scope.data = e.data; angular.forEach($scope.data, function (itemFirst, keyFirst) { itemFirst.data_product_array = []; var referralArray = []; referralArray.push(parseInt(itemFirst.referral_id)); angular.forEach(itemFirst.referral_sub_array, function (item, key) { referralArray.push(parseInt(item.referral_id)); }); var product = { 'referral_id': itemFirst.referral_id, 'product_array': [] }; var jsonFilterProduct = { /*'badge_id_query': [18],*/ 'referral_id_array_in': referralArray, /*$scope.data[i].referral_id*/ }; if (typeof badgeId !== 'undefined' && badgeId != 0) { jsonFilterProduct.badge_id_query = "((18 AND " + badgeId + "))"; } else { if($scope.featured == 'true'){ jsonFilterProduct.badge_id_array = [18,16]; }else{ jsonFilterProduct.badge_id_array = [18]; } } var dd = { 'cur_page': 1, 'per_page': (itemFirst.referral_image.length <= 0) ? 12 : 9, 'txt_sortby': '', 'txt_filter_json': JSON.stringify(jsonFilterProduct) }; GAEAPI.get('product/lists', dd, $scope).then(function (ee) { console.log("getProduct IN Ref", dd, ee); if (ee.data.dataList.length) { /*product.product_array = ee.data.dataList; $scope.data_product.push(product);*/ itemFirst.data_product_array = ee.data.dataList; $scope.product_length = ee.data.dataList.length; } $scope.data_done = true; }); }); } }); }; $scope.getData(); /* Check if seo enable */ $scope.checkSeo = function () { return (GURL.isHtml5Mode()) ? true : false; }; /* * query by badge in category * @params {referralId} referral id of category (parent category) * @params {targetBadgeId} badge id (new arrival,recommend,featured) * @return array (in category object) * */ $scope.testytest = 16; $scope.view_ft = []; $scope.viewTab = 0; for(var ft = 0;ft<200;ft++){ $scope.view_ft[ft] = 16; } $scope.viewcatlist = []; $scope.previousDataTab = []; $scope.switchTab = function (referralId, targetBadgeId,index) { $scope.viewcatlist[index] = 16; $scope.viewcatlist[index] = referralId+'-'+targetBadgeId; $scope.viewTab = referralId+'-'+targetBadgeId; $scope.view_ft[index] = 18; var r = []; angular.forEach($scope.data, function (item) { var r = []; r.push(parseInt(item.referral_id)); angular.forEach(item.referral_sub_array, function (itemSub, keySub) { r.push(parseInt(itemSub.referral_id)); }); if (item.referral_id == referralId) { /* if parent referral id match */ $scope.previousDataTab[referralId] = item.data_product_array; item.data_product_array = []; var jsonFilterProduct = { 'referral_id_array_in': r, 'badge_id_array': [targetBadgeId], }; var dataSend = { 'cur_page': 1, 'per_page': (item.referral_image.length <= 0) ? 12 : 9, 'txt_sortby': '', 'txt_filter_json': JSON.stringify(jsonFilterProduct) }; GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok == 1 && e.data.dataList.length) { item.data_product_array = e.data.dataList; } else { item.data_product_array = $scope.previousDataTab[referralId]; } console.log("getProduct IN Ref => Tab", dataSend, e); return; }); } }); }; $scope._makeProductToCarousel = function (keyCustom, type) { var elementName = '[data-id="' + keyCustom + '"]'; var optionsParmas = { autoplay: (window.location.host !== 'localhost') ? true : false, slidesToShow: 1, slidesToScroll: 1, dots: true, arrows: false, centerMode: false, infinite: true, variableWidth: false, }; }; /* Calculate Product Block for Arrows */ $scope.calculateProductBlock = function(){ return "-" + (($('.row.slick-slider[data-id="'+$scope._uniqueKey+'"]').height() / 2) + 34) + "px"; }; /* Carousel Arrow Click */ $scope._slickGoLeft = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickPrev'); }, 100); }; /* Carousel Arrow Click */ $scope._slickGoRight = function () { $timeout(function () { $('[data-id="' + $scope._uniqueKey + '"]').slick('slickNext'); }, 100); }; $scope.displayImage = function(image_url, prefix) {return GAEAPI.getGaeImageUrl(image_url, prefix);} /* Event Listener when ng-repeat end */ $rootScope.$on('repeatend', function() { $timeout(function(){ if($('.gallery-block[data-id]').length){ $('.gallery-block[data-id]').not('.slick-initialized').each(function(Key,Object){ if($(this).find('.imageItem').length > 0){ $scope._makeProductToCarousel($(this).attr('data-id'), 'gallery'); } }); } },500); }); /*angular.element($window).bind('load', function(){*/ }; return promise; }); _ui_share_app.filter('productPriceFilter', function() { return function(items, inputConfig,inasa) { var filtered = []; var min = parseInt(inputConfig.min); var max = parseInt(inputConfig.max); angular.forEach(items, function(item) { if (parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { filtered.push(item); } }); return filtered; }; }); _ui_share_app.directive('productPageTypeO', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productPageTypeO'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $timeout(function() { $scope.viewType = view_type; $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { /*var id = parseInt(v); var test = $scope.viewRouteParams().badge.indexOf(parseInt(v)) !== -1; if(test){ switch(id){ case 72: $scope.filter_new = true; break; case 74: $scope.filter_rec = true; break; case 75: $scope.filter_best = true; break; case 16: $scope.filter_fea = true; break; } } return test;*/ }; $scope.doFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } /* check sort */ // if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { // var refOArray = $routeParams.referral_array.split(','); // if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { // json_filter.referral_id_array_in = refOArray; // } else { // json_filter.referral_id_array_in = [refOArray]; // } // } console.log("json_filter.referral_id_array_in :" , json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); if($(window).height() > 595){ $('.erere').css('min-height',(($(window).height() - 145)+'px')); // alert($(window).height() - 145); } angular.element($window).bind('scroll', function() { var curPos = ($(document).scrollTop()); var properHeight = ($('.erere').height()); console.debug("Cur pos", curPos, properHeight); if($(window).width() > 991){ if ((curPos + ($(window).height() - 145)) > properHeight ) { if ((properHeight - curPos) <= ($(window).height() - 145)) { if(properHeight - ($(window).height() - 145) < 0){ /* document.getElementsByClassName('testrewq')[0].style.top = "0px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = "0px"; */ $('.testrewq').css('top','0px'); $('.testrewq').css('margin-bottom','0px'); }else{ $('.testrewq').css('top',(properHeight - ($(window).height() - 145)) + 'px'); $('.testrewq').css('margin-bottom',(properHeight - ($(window).height() - 145)) + 'px'); /* document.getElementsByClassName('testrewq')[0].style.top = (properHeight - ($(window).height() - 145)) + "px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = (properHeight - ($(window).height() - 145)) + "px"; */ } } else { $('.testrewq').css('top','auto'); /* document.getElementsByClassName('testrewq')[0].style.top = "auto"; */ } angular.element('.testrewq').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { $('.testrewq').css('top','auto'); /* document.getElementsByClassName('testrewq')[0].style.top = "auto"; */ angular.element('.testrewq').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }else{ angular.element('.testrewq').removeClass('unactive'); } }); }; return promise; });_ui_share_app.directive('productPageTypeOa', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', feature: '@feature', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarousel = function(elem) { $('.product-page-type-oa').css('height', '0'); $('.product-page-type-oa').css('opacity', '0'); setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: true, autoplay: false, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1330, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { slidesToShow: 4, } }, { breakpoint: 768, settings: { slidesToShow: 1, } }, { breakpoint: 480, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); $('.product-page-type-oa').css('height', 'auto'); $('.product-page-type-oa').css('opacity', '1'); }, 1000); }; $scope._useTopBar = (typeof $scope.topbar !== 'undefined' && $scope.topbar == 'true') ? true : false; $scope._useBadge = (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != '0' && $scope.badgeid != '') ? true : false; $scope._useFeature = (typeof $scope.feature !== 'undefined' && $scope.feature != '0' && $scope.feature != '') ? true : false; $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || ''; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '12'; $scope.changefilterPerPageData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { /* code */ }; $scope.doFilterBy = function(isChecked, badgeId) { /* code */ }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; $scope.viewdata = 'grid'; $scope.getTimes = 1; $scope.data = []; $scope.loading = false; $scope.done = false; $scope.noProduct = false; $scope.noMore = false; $scope.watchCallbackArray = function() { var r = []; var max = 12; if ($scope.limit > 0) { max = $scope.limit; } for (var i = 0; i < max; i++) { r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }], product_badge: [{ badge_id: 18 }], callback_array: true }); } return r; }; /* get data product */ $scope.fetchTime = 1; $scope.getDataAll = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } /* check sort */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } $scope.loading = true; var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 10, 'txt_sortby': ($scope.filterSortData != "") ? $scope.filterSortData : 'product_lastest_create', 'txt_filter_json': JSON.stringify(json_filter), }; GAEAPI.get('product/lists', dataSend).then(function(e) { console.log("Lightmax: getDataProduct: e", e); $scope.done = true; $scope.loading = false; if (e.ok == 1 && e.data.dataList.length) { if ($scope.data.length) { var curData = $scope.data; $scope.data = curData.concat(e.data.dataList); } else { $scope.data = e.data.dataList; } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } if (e.data.dataList.length < parseInt(dataSend.per_page)) { $scope.noMore = true; } console.log("Lightmax: getDataProduct: dataSend : noMore ", e.data.dataList.length < parseInt(dataSend.per_page), e.data.dataList.length, parseInt(dataSend.per_page)); }); }; /* Get data * @params badgeid = badge id * @return array */ $scope.getData = function(badgeId) { if ($scope.noProduct) { return; } var txt_filter = {}; /* Check Badge */ if(typeof $scope.feature !== 'undefined' && $scope.feature !== '' && $scope.feature !== false){ if (typeof badgeId !== 'undefined' && badgeId !== '' && badgeId !== 0) { txt_filter.badge_id_array = [16, badgeId]; } else { txt_filter.badge_id_array = [16]; } }else{ if (typeof badgeId !== 'undefined' && badgeId !== '' && badgeId !== 0) { txt_filter.badge_id_array = [18, badgeId]; } else { txt_filter.badge_id_array = [18]; } } $scope.loading = true; var d = { 'cur_page': ($scope.getTimes > 1) ? $scope.getTimes : 1, 'per_page': $scope.limit || 8, 'txt_filter_json': JSON.stringify(txt_filter) }; GAEAPI.get('product/lists', d, $scope).then(function(e) { $scope.loadMore_is_load = false; console.log("Lightmax: getBadgeProduct: dataSend", d); if (e.ok == 1) { if (e.data.dataList.length) { if (!$scope.data.length) { $scope.data = e.data.dataList; } else if ($scope.data.length > 0) { var currentData = $scope.data; $scope.data = currentData.concat(e.data.dataList); } } else { /*var dataDummy = $scope.watchCallbackArray(); if(!$scope.data.length){ $scope.data = dataDummy; } else if($scope.data.length > 0){ var currentData = $scope.data; $scope.data = currentData.concat(dataDummy); }*/ } } $scope.loading = false; $scope.done = true; if (e.data.dataList.length < parseInt(d.per_page)) { $scope.noMore = true; } console.log("Lightmax: getBadgeProduct: dataSend : noMore ", e.data.dataList.length < parseInt(d.per_page), e.data.dataList.length, parseInt(d.per_page)); }); }; if (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != "" && $scope.badgeid != 0) { $scope.getData($scope.badgeid); } else { $scope.getDataAll(); } $scope.checkNoMoreProduct = function() { var t = (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != "" && $scope.badgeid != 0) ? $scope.getTimes : $scope.fetchTime; var p = $scope.data.length; if (t <= 1 && p <= $scope.limit) { $scope.noProduct = true; } else if (t > 1 && p <= ($scope.limit * t)) { $scope.noProduct = true; } }; /* load more product */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.loadMore_is_load = true; if (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != "" && $scope.badgeid != 0) { $scope.getTimes = $scope.getTimes + 1; return $scope.getData($scope.badgeid); } else { $scope.fetchTime = $scope.fetchTime + 1; return $scope.getDataAll(); } }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* Display badge name */ $scope.diplayName = function() { var str = '', badgeTest = parseInt($scope.badgeid); switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'สินค้าใหม่'; break; case 74: str = 'สินค้าแนะนำ'; break; case 75: str = 'สินค้าขายดี'; break; } return str; }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); var path = { root_id: $scope.viewRouteParams().root_id, referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, referral_name: $scope.viewRouteParams().referral_name, badge: badgeIdArray, sort: $scope.filterSortData, perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { if (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != "" && $scope.badgeid != 0) { $scope.getData($scope.badgeid); } else { $scope.getDataAll(); } }); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend-product .-recommend-product[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend-product .-recommend-product[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.viewDataSize = function(name) { return -($(".item-product-" + name).height() + 100); }; }; return promise; });_ui_share_app.filter('productPriceFilter', function() { return function(items, inputConfig,inasa) { var filtered = []; var min = parseInt(inputConfig.min); var max = parseInt(inputConfig.max); angular.forEach(items, function(item) { if (parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { filtered.push(item); } }); return filtered; }; }); _ui_share_app.directive('productPageTypeOaa', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productPageTypeOaa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', componentcart: '@componentcart', fontcolor: '@fontcolor', imgbutton: '@imgbutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $timeout(function() { $scope.viewType = view_type; $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { /*var id = parseInt(v); var test = $scope.viewRouteParams().badge.indexOf(parseInt(v)) !== -1; if(test){ switch(id){ case 72: $scope.filter_new = true; break; case 74: $scope.filter_rec = true; break; case 75: $scope.filter_best = true; break; case 16: $scope.filter_fea = true; break; } } return test;*/ }; $scope.doFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } /* check sort */ // if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { // var refOArray = $routeParams.referral_array.split(','); // if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { // json_filter.referral_id_array_in = refOArray; // } else { // json_filter.referral_id_array_in = [refOArray]; // } // } console.log("json_filter.referral_id_array_in :" , json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); if($(window).height() > 595){ $('.erere').css('min-height',(($(window).height() - 145)+'px')); // alert($(window).height() - 145); } angular.element($window).bind('scroll', function() { var curPos = ($(document).scrollTop()); var properHeight = ($('.erere').height()); console.debug("Cur pos", curPos, properHeight); if($(window).width() > 991){ if ((curPos + ($(window).height() - 145)) > properHeight ) { if ((properHeight - curPos) <= ($(window).height() - 145)) { if(properHeight - ($(window).height() - 145) < 0){ /* document.getElementsByClassName('testrewq')[0].style.top = "0px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = "0px"; */ $('.testrewq').css('top','0px'); $('.testrewq').css('margin-bottom','0px'); }else{ $('.testrewq').css('top',(properHeight - ($(window).height() - 145)) + 'px'); $('.testrewq').css('margin-bottom',(properHeight - ($(window).height() - 145)) + 'px'); /* document.getElementsByClassName('testrewq')[0].style.top = (properHeight - ($(window).height() - 145)) + "px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = (properHeight - ($(window).height() - 145)) + "px"; */ } } else { $('.testrewq').css('top','auto'); /* document.getElementsByClassName('testrewq')[0].style.top = "auto"; */ } angular.element('.testrewq').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { $('.testrewq').css('top','auto'); /* document.getElementsByClassName('testrewq')[0].style.top = "auto"; */ angular.element('.testrewq').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }else{ angular.element('.testrewq').removeClass('unactive'); } }); }; return promise; });_ui_share_app.filter('productPriceFilter', function() { return function(items, inputConfig,inasa) { var filtered = []; var min = parseInt(inputConfig.min); var max = parseInt(inputConfig.max); angular.forEach(items, function(item) { if (parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { filtered.push(item); } }); return filtered; }; }); _ui_share_app.directive('productPageTypeOab', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productPageTypeOab'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $timeout(function() { $scope.viewType = view_type; $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { /*var id = parseInt(v); var test = $scope.viewRouteParams().badge.indexOf(parseInt(v)) !== -1; if(test){ switch(id){ case 72: $scope.filter_new = true; break; case 74: $scope.filter_rec = true; break; case 75: $scope.filter_best = true; break; case 16: $scope.filter_fea = true; break; } } return test;*/ }; $scope.doFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } /* check sort */ // if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { // var refOArray = $routeParams.referral_array.split(','); // if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { // json_filter.referral_id_array_in = refOArray; // } else { // json_filter.referral_id_array_in = [refOArray]; // } // } console.log("json_filter.referral_id_array_in :" , json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // if($(window).height() > 595){ // $('.erere').css('min-height',(($(window).height() - 145)+'px')); // } /* angular.element($window).bind('scroll', function() { var curPos = ($(document).scrollTop()); var properHeight = ($('.erere').height()); console.debug("Cur pos", curPos, properHeight); if($(window).width() > 991){ if ((curPos + ($(window).height() - 145)) > properHeight ) { if ((properHeight - curPos) <= ($(window).height() - 145)) { if(properHeight - ($(window).height() - 145) < 0){ $('.testrewq').css('top','0px'); $('.testrewq').css('margin-bottom','0px'); }else{ $('.testrewq').css('top',(properHeight - ($(window).height() - 145)) + 'px'); $('.testrewq').css('margin-bottom',(properHeight - ($(window).height() - 145)) + 'px'); } } else { $('.testrewq').css('top','auto'); } angular.element('.testrewq').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { $('.testrewq').css('top','auto'); angular.element('.testrewq').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }else{ angular.element('.testrewq').removeClass('unactive'); } }); */ }; return promise; });_ui_share_app.directive('productPageTypeOb', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { /* console.log('productPageTypeOb : ', name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = "สินค้าทั้งหมด"; $scope.sub_products = "0"; $scope.state = ""; $scope.dataArray6113 = []; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.dataBrandArray = []; $scope.dataBrandArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "สินค้าทั้งหมด"; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "สินค้าทั้งหมด"; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 100 }; $scope.getData().dataSend('referral/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataBrandArray = output.data.dataList; $scope.dataBrandArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "สินค้าทั้งหมด"; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.sub_products = params.referral_id; if (output.data == 0) { $scope.state = "sub_category_products"; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 100 }; $scope.getData().dataSend('referral/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataBrandArray = output.data.dataList; $scope.dataBrandArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.sub_products = params.sendtag; var dataSend = { 'txt_referral_id': 6113 }; $scope.getData().dataSend('referral/id_map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray6113 = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "สินค้าใหม่"; } else if (params.badge_id == "74") { $scope.cover_top = "สินค้าแนะนำ"; } else if (params.badge_id == "75") { $scope.cover_top = "สินค้าขายดี"; } $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_lastest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().brand || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('productPageTypeOba', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOba'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = "สินค้าและบริการ"; $scope.sub_products = "0"; $scope.state = ""; $scope.dataArray6113 = []; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "สินค้าและบริการ"; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "สินค้าและบริการ"; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "สินค้าและบริการ"; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; if (output.data == 0) { $scope.state = "sub_category_products"; $scope.sub_products = params.referral_id; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.sub_products = params.sendtag; var dataSend = { 'txt_referral_id': 6113 }; $scope.getData().dataSend('referral/id_map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray6113 = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "สินค้าใหม่"; } else if (params.badge_id == "74") { $scope.cover_top = "สินค้าขายดี"; } else if (params.badge_id == "75") { $scope.cover_top = "สินค้าแนะนำ"; } $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().badge || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('productPageTypeObb', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeObb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeObb : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = "สินค้าทั้งหมด"; $scope.sub_products = "0"; $scope.state = ""; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArrayMain = []; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.dataBrandArray = []; $scope.dataBrandArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "สินค้าทั้งหมด"; $scope.state = "main_category"; var jsonFilter = { 'badge_id_array': [18] }; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "สินค้าทั้งหมด"; $scope.state = "sub_category"; var jsonFilter = { 'badge_id_array': [18] }; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); /* var dataSend = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 100 }; $scope.getData().dataSend('referral/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataBrandArray = output.data.dataList; $scope.dataBrandArrayState = $scope.getData().stateData(false, true); }); }); */ } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "สินค้าทั้งหมด"; $scope.state = "sub_category"; var jsonFilter = { 'badge_id_array': [18] }; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.sub_products = params.referral_id; if (output.data == 0) { $scope.state = "sub_category_products"; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); /* var dataSend = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 100 }; $scope.getData().dataSend('referral/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataBrandArray = output.data.dataList; $scope.dataBrandArrayState = $scope.getData().stateData(false, true); }); }); */ } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "สินค้าใหม่"; } else if (params.badge_id == "74") { $scope.cover_top = "สินค้าขายดี"; } else if (params.badge_id == "75") { $scope.cover_top = "สินค้าแนะนำ"; } $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } else { if (typeof data.sort != 'undefined' && data.sort !== "") { page += '?sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('productPageTypeObba', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeObba'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeObba : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = "หมวดหมู่ทั้งหมด"; $scope.sub_products = "0"; $scope.state = ""; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArrayMain = []; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.dataBrandArray = []; $scope.dataBrandArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "หมวดหมู่ทั้งหมด"; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "หมวดหมู่ทั้งหมด"; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); /* var dataSend = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 100 }; $scope.getData().dataSend('referral/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataBrandArray = output.data.dataList; $scope.dataBrandArrayState = $scope.getData().stateData(false, true); }); }); */ } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "หมวดหมู่ทั้งหมด"; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.sub_products = params.referral_id; if (output.data == 0) { $scope.state = "sub_category_products"; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); /* var dataSend = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 100 }; $scope.getData().dataSend('referral/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataBrandArray = output.data.dataList; $scope.dataBrandArrayState = $scope.getData().stateData(false, true); }); }); */ } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "สินค้าใหม่"; } else if (params.badge_id == "74") { $scope.cover_top = "สินค้าขายดี"; } else if (params.badge_id == "75") { $scope.cover_top = "สินค้าแนะนำ"; } $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('productPageTypeObc', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeObc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', home: '@home', category: '@category', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log(name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.home = (typeof $scope.home == undefined && $scope.home == '') ? "หน้าแรก" : $scope.home; $scope.category = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.cover_top = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.sub_products = "0"; $scope.state = ""; $scope.dataArray6113 = []; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = (typeof $scope.category == undefined && $scope.category == '') ? "สินค้า" : $scope.category; $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; if (output.data == 0) { $scope.state = "sub_category_products"; $scope.sub_products = params.referral_id; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.sub_products = params.sendtag; var dataSend = { 'txt_referral_id': 6113 }; $scope.getData().dataSend('referral/id_map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray6113 = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "สินค้าใหม่"; } else if (params.badge_id == "74") { $scope.cover_top = "สินค้าขายดี"; } else if (params.badge_id == "75") { $scope.cover_top = "สินค้าแนะนำ"; } $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().badge || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('productPageTypeOc', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._params = $routeParams.referral_id; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.getRelation($scope._viewRouteParams().referral_id); $scope.filterbadge = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadge = function(input) { $scope.filterbadge = input; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterBadgeData = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadgeselect = function() { $scope.filterbadge = $scope.filterBadgeData; // alert($scope.filterbadge); // return; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterSortData = $scope._viewRouteParams().sort || 'product_category_sort_index_asc'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewdata = $routeParams.view || 'grid'; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.viewTypeSet = function(view_type){ $timeout(function() { $scope.viewdata = view_type; $scope.pathChange(); }, 300); }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } $scope.$watch('_params', function(newValue, oldValue) { if (newValue) { $scope.getcatidname(newValue); } }); $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.diplayName = function() { var str = '', badgeTest = parseInt($scope.badgeid); switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'New Arrival'; break; case 74: str = 'Recommend'; break; case 75: str = 'Best Seller'; break; } return str; }; $scope.pathChange = function() { var buildOtherReferral = function() {}; var path = { sendtag: $scope._viewRouteParams().sendtag, root_id: $scope._viewRouteParams().root_id, referral_id: $scope._viewRouteParams().referral_id, referral_type: 'category', sort: $scope.filterSortData, view: $scope.viewdata, badge: $scope.filterbadge, }; var strHref = 'category-lists'; if (typeof path.sendtag !== 'undefined' && path.sendtag !== "") { strHref += '&sendtag=' + path.sendtag; } else { delete path.sendtag; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge; } else { delete path.badge; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.sort; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { if ($routeParams.referral_id) { $scope.FetchDisplayCategorylists($routeParams.referral_id); } else { $scope.FetchDisplayCategory(); } }); $scope.name_rootcat = false; $scope.getcatidname = function() {}; }; return promise; });_ui_share_app.directive('productPageTypeOca', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOca'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { menu: '@menu', text: '@text', cardgrid: '@cardgrid', cardlist: '@cardlist', styletextgrid: '@styletextgrid', stylebuttongrid: '@stylebuttongrid', imgcartgrid: '@imgcartgrid', styletextlist: '@styletextlist', stylebuttonlist: '@stylebuttonlist', imgcartlist: '@imgcartlist', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.shopId = '0'; $scope.getShopId = function() { $scope.shopId = CUR_THEME.shop_id(); }; $scope.getShopId(); $scope.returnJson = function(data, callback) { var json = JSON.parse(data); callback(json); }; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeObb : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = $scope.text; $scope.sub_products = "0"; $scope.state = ""; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArrayMain = []; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { console.log('referral/id : output : ', output); $scope.cover_top = output.data.referral_name; if (output.data.referral_image.length != 0) { $scope.cover_background_image_top = output.data.referral_image[0].image_url; } }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.sub_products = params.referral_id; if (output.data == 0) { $scope.state = "sub_category_products"; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.cover_background_image_top = ""; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "NEW PRODUCT"; } else if (params.badge_id == "74") { $scope.cover_top = "BEST SELLER"; } else if (params.badge_id == "75") { $scope.cover_top = "RECOMMEND"; } $scope.cover_background_image_top = ""; $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_lastest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData, price: $scope.price }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; $scope.price = { min: 0, max: 9999999 }; $scope.setPrice = function() { console.log("setPrice : price : ", $scope.price); }; }; return promise; });_ui_share_app.directive('productPageTypeOcb', function($rootScope, $routeParams, $location ,shareService) { var templateName = 'productPageTypeOcb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', component: '@component', texthead: '@texthead', stylebutton: '@stylebutton', lang: '@lang', styletext: '@styletext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window ) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._params = $routeParams.referral_id; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component != '') ? $scope.component : 'ub'; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && $scope.stylebutton != '') ? $scope.stylebutton : 'outlined_button_small'; $scope.shop_id = CUR_THEME.shop_id(); $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d, $scope).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.getRelation($scope._viewRouteParams().referral_id); $scope.filterbadge = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadge = function(input) { $scope.filterbadge = input; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterBadgeData = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadgeselect = function() { $scope.filterbadge = $scope.filterBadgeData; // alert($scope.filterbadge); // return; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewdata = $routeParams.view || 'grid'; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.viewTypeSet = function(view_type) { $timeout(function() { $scope.viewdata = view_type; $scope.pathChange(); }, 300); }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var json_filter = { badge_id_array: ["18"] }; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify(json_filter), }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } $scope.$watch('_params', function(newValue, oldValue) { if (newValue) { $scope.getcatidname(newValue); } }); $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.diplayName = function() { var str = '', badgeTest = parseInt($scope.badgeid); switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'New Arrival'; break; case 74: str = 'Recommend'; break; case 75: str = 'Best Seller'; break; } return str; }; $scope.diplayNameShow = function(badgeid) { var str = '', badgeTest = parseInt(badgeid); if ($scope.lang == 'th') { switch (badgeTest) { case 16: str = 'สินค้าเด่น'; break; case 72: str = 'สินค้าใหม่'; break; case 74: str = 'สินค้าแนะนำ'; break; case 75: str = 'สินค้าขายดี'; break; } } else { switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'New Arrival'; break; case 74: str = 'Recommend'; break; case 75: str = 'Best Seller'; break; } } return str; }; $scope.pathChange = function() { var buildOtherReferral = function() {}; var path = { sendtag: $scope._viewRouteParams().sendtag, root_id: $scope._viewRouteParams().root_id, referral_id: $scope._viewRouteParams().referral_id, referral_type: 'category', sort: $scope.filterSortData, view: $scope.viewdata, badge: $scope.filterbadge, }; var strHref = 'category-lists'; if (typeof path.sendtag !== 'undefined' && path.sendtag !== "") { strHref += '&sendtag=' + path.sendtag; } else { delete path.sendtag; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge; } else { delete path.badge; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.sort; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { if ($routeParams.referral_id) { $scope.FetchDisplayCategorylists($routeParams.referral_id); } else { $scope.FetchDisplayCategory(); } }); $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.name_rootcat = false; $scope.getcatidname = function() {}; }; return promise; });_ui_share_app.directive('productPageTypeOcc', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOcc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { menu: '@menu', text: '@text', cardgrid: '@cardgrid', cardlist: '@cardlist', styletextgrid: '@styletextgrid', stylebuttongrid: '@stylebuttongrid', imgcartgrid: '@imgcartgrid', styletextlist: '@styletextlist', stylebuttonlist: '@stylebuttonlist', imgcartlist: '@imgcartlist', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.shopId = '0'; $scope.getShopId = function() { $scope.shopId = CUR_THEME.shop_id(); }; $scope.getShopId(); $scope.returnJson = function(data, callback) { var json = JSON.parse(data); callback(json); }; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeObb : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = $scope.text; $scope.sub_products = "0"; $scope.state = ""; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArrayMain = []; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { console.log('referral/id : output : ', output); $scope.cover_top = output.data.referral_name; if (output.data.referral_image.length != 0) { $scope.cover_background_image_top = output.data.referral_image[0].image_url; } }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = $scope.text; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.sub_products = params.referral_id; if (output.data == 0) { $scope.state = "sub_category_products"; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.cover_background_image_top = ""; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "NEW PRODUCT"; } else if (params.badge_id == "74") { $scope.cover_top = "BEST SELLER"; } else if (params.badge_id == "75") { $scope.cover_top = "RECOMMEND"; } $scope.cover_background_image_top = ""; $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_lastest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData, price: $scope.price }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; $scope.price = { min: 0, max: 9999999 }; $scope.setPrice = function() { console.log("setPrice : price : ", $scope.price); }; }; return promise; });_ui_share_app.directive('productPageTypeOd', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOd'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._params = $routeParams.referral_id; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d, $scope).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.getRelation($scope._viewRouteParams().referral_id); $scope.filterbadge = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadge = function(input) { $scope.filterbadge = input; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewdata = 'grid'; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } $scope.$watch('_params', function(newValue, oldValue) { if (newValue) { $scope.getcatidname(newValue); } }); $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.diplayName = function() { var str = '', badgeTest = parseInt($scope.badgeid); switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'New Arrival'; break; case 74: str = 'Recommend'; break; case 75: str = 'Best Seller'; break; } return str; }; $scope.pathChange = function() { var buildOtherReferral = function() {}; var path = { sendtag: $scope._viewRouteParams().sendtag, root_id: $scope._viewRouteParams().root_id, referral_id: $scope._viewRouteParams().referral_id, referral_type: 'category', sort: $scope.filterSortData, badge: $scope.filterbadge, }; var strHref = 'category-lists'; if (typeof path.sendtag !== 'undefined' && path.sendtag !== "") { strHref += '&sendtag=' + path.sendtag; } else { delete path.sendtag; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge; } else { delete path.badge; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { if ($routeParams.referral_id) { $scope.FetchDisplayCategorylists($routeParams.referral_id); } else { $scope.FetchDisplayCategory(); } }); $scope.name_rootcat = false; $scope.getcatidname = function() {}; }; return promise; });_ui_share_app.directive('productPageTypeOe', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOe'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', promotion: '@promotion', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.mkCarousel = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: false, arrows: false, autoplay: false, autoplaySpeed: 4000, slidesToShow: 4, slidesToScroll: 1, infinite: false, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 4, } }, { breakpoint: 991, settings: { slidesToShow: 4, } }, { breakpoint: 768, settings: { slidesToShow: 1, } }, { breakpoint: 480, settings: { slidesToShow: 1, } }] }).closest('section').addClass('active'); }, 1000); }; $scope._useTopBar = (typeof $scope.topbar !== 'undefined' && $scope.topbar == 'true') ? true : false; $scope._useBadge = (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != '0' && $scope.badgeid != '') ? true : false; $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || ''; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '12'; $scope.changefilterPerPageData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { /* code */ }; $scope.doFilterBy = function(isChecked, badgeId) { /* code */ }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; $scope.viewdata = 'grid'; $scope.getTimes = 1; $scope.data = []; $scope.loading = false; $scope.done = false; $scope.noProduct = false; $scope.noMore = false; $scope.watchCallbackArray = function() { var r = []; var max = 12; if ($scope.limit > 0) { max = $scope.limit; } for (var i = 0; i < max; i++) { r.push({ product_id: '999999', product_title: 'Samsung Galaxy S8', product_price: '45000', product_compare_price: '55000', product_image: [{ image_url: 'extensions/themes/gae_default301/staticfiles/images/default/490x490.gif' }], product_badge: [{ badge_id: 18 }], callback_array: true }); } return r; }; /* get data product */ $scope.fetchTime = 1; $scope.getDataAll = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } /* check sort */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } $scope.loading = true; var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 10, 'txt_sortby': ($scope.filterSortData != "") ? $scope.filterSortData : 'product_lastest_create', 'txt_filter_json': JSON.stringify(json_filter), }; GAEAPI.get('product/lists', dataSend).then(function(e) { console.log("Lightmax: getDataProduct: e", e); $scope.done = true; $scope.loading = false; if (e.ok == 1 && e.data.dataList.length) { if ($scope.data.length) { var curData = $scope.data; $scope.data = curData.concat(e.data.dataList); } else { $scope.data = e.data.dataList; } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } if (e.data.dataList.length < parseInt(dataSend.per_page)) { $scope.noMore = true; } console.log("Lightmax: getDataProduct: dataSend : noMore ", e.data.dataList.length < parseInt(dataSend.per_page), e.data.dataList.length, parseInt(dataSend.per_page)); }); }; $scope._getProductListAll = function () { $scope.data = []; var jsonFilter = { 'badge_id_array': [18] }; var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify(jsonFilter) }; GAEAPI.get('product/lists', dataSend).then(function (e) { if (e.ok == 1) { for (var i = 0; i < e.data.dataList.length ; i++) { if(e.data.dataList[i].product_discount.length != 0){ $scope.data.push(e.data.dataList[i]); } } console.log("spdosdpsidpsdisodi :",$scope.data); } }); }; /* Get data * @params badgeid = badge id * @return array */ $scope.getData = function(badgeId) { if ($scope.noProduct) { return; } var txt_filter = {}; /* Check Badge */ if (typeof badgeId !== 'undefined' && badgeId !== '' && badgeId !== 0) { txt_filter.badge_id_array = [18, badgeId]; } else { txt_filter.badge_id_array = [18]; } $scope.loading = true; var d = { 'cur_page': ($scope.getTimes > 1) ? $scope.getTimes : 1, 'per_page': $scope.limit || 8, 'txt_filter_json': JSON.stringify(txt_filter) }; GAEAPI.get('product/lists', d, $scope).then(function(e) { $scope.loadMore_is_load = false; console.log("Lightmax: getBadgeProduct: dataSend", d); if (e.ok == 1) { if (e.data.dataList.length) { if (!$scope.data.length) { $scope.data = e.data.dataList; } else if ($scope.data.length > 0) { var currentData = $scope.data; $scope.data = currentData.concat(e.data.dataList); } } else { /*var dataDummy = $scope.watchCallbackArray(); if(!$scope.data.length){ $scope.data = dataDummy; } else if($scope.data.length > 0){ var currentData = $scope.data; $scope.data = currentData.concat(dataDummy); }*/ } } $scope.loading = false; $scope.done = true; if (e.data.dataList.length < parseInt(d.per_page)) { $scope.noMore = true; } console.log("Lightmax: getBadgeProduct: dataSend : noMore ", e.data.dataList.length < parseInt(d.per_page), e.data.dataList.length, parseInt(d.per_page)); }); }; if (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != "" && $scope.badgeid != 0) { $scope.getData($scope.badgeid); }else if(typeof $scope.promotion !== undefined && $scope.promotion == 'true'){ $scope._getProductListAll(); } else { $scope.getDataAll(); } $scope.checkNoMoreProduct = function() { var t = (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != "" && $scope.badgeid != 0) ? $scope.getTimes : $scope.fetchTime; var p = $scope.data.length; if (t <= 1 && p <= $scope.limit) { $scope.noProduct = true; } else if (t > 1 && p <= ($scope.limit * t)) { $scope.noProduct = true; } }; /* load more product */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.loadMore_is_load = true; if (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != "" && $scope.badgeid != 0) { $scope.getTimes = $scope.getTimes + 1; return $scope.getData($scope.badgeid); } else { $scope.fetchTime = $scope.fetchTime + 1; return $scope.getDataAll(); } }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* Display badge name */ $scope.diplayName = function() { var str = '', badgeTest = parseInt($scope.badgeid); switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'NEW ARRIVAL'; break; case 74: str = 'RECOMMEND'; break; case 75: str = 'BEST SELLERS'; break; } return str; }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); var path = { root_id: $scope.viewRouteParams().root_id, referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, referral_name: $scope.viewRouteParams().referral_name, badge: badgeIdArray, sort: $scope.filterSortData, perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { if (typeof $scope.badgeid !== 'undefined' && $scope.badgeid != "" && $scope.badgeid != 0) { $scope.getData($scope.badgeid); }else if(typeof $scope.promotion !== undefined && $scope.promotion == 'true'){ $scope._getProductListAll(); } else { $scope.getDataAll(); } }); $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend-product .-recommend-product[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend-product .-recommend-product[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; $scope.openCity = function(evt, cityName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassName("tabcontent"); for (i = 0; i < tabcontent.length; i++) { tabcontent[i].style.display = "none"; } tablinks = document.getElementsByClassName("tablinks"); for (i = 0; i < tablinks.length; i++) { tablinks[i].className = tablinks[i].className.replace(" active", ""); } document.getElementById(cityName).style.display = "block"; evt.currentTarget.className += " active"; } $scope.viewDataSize = function(name) { return -($(".item-product-" + name).height() + 100); }; }; return promise; });_ui_share_app.directive('productPageTypeOf', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOf'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: "@component", badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._params = $routeParams.referral_id; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.getRelation($scope._viewRouteParams().referral_id); $scope.filterbadge = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadge = function(input) { $scope.filterbadge = input; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewdata = 'grid'; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } $scope.$watch('_params', function(newValue, oldValue) { if (newValue) { $scope.getcatidname(newValue); } }); $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.diplayName = function() { var str = '', badgeTest = parseInt($scope.badgeid); switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'New Arrival'; break; case 74: str = 'Recommend'; break; case 75: str = 'Best Seller'; break; } return str; }; $scope.pathChange = function() { var buildOtherReferral = function() {}; var path = { sendtag: $scope._viewRouteParams().sendtag, root_id: $scope._viewRouteParams().root_id, referral_id: $scope._viewRouteParams().referral_id, referral_type: 'category', sort: $scope.filterSortData, badge: $scope.filterbadge, }; var strHref = 'category-lists'; if (typeof path.sendtag !== 'undefined' && path.sendtag !== "") { strHref += '&sendtag=' + path.sendtag; } else { delete path.sendtag; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge; } else { delete path.badge; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { if ($routeParams.referral_id) { $scope.FetchDisplayCategorylists($routeParams.referral_id); } else { $scope.FetchDisplayCategory(); } }); $scope.name_rootcat = false; $scope.getcatidname = function() {}; }; return promise; });_ui_share_app.directive('productPageTypeOg', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOg'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._params = $routeParams.referral_id; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.getRelation($scope._viewRouteParams().referral_id); $scope.filterbadge = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadge = function(input) { $scope.filterbadge = input; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterSortData = $scope._viewRouteParams().sort || 'product_category_sort_index_asc'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewType = 'grid'; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var j = { "badge_id_array_for_root": [18] }; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /*$scope.$watch('_params', function(newValue, oldValue) { if (newValue) { $scope.getcatidname(newValue); } });*/ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.diplayName = function() { var str = '', badgeTest = parseInt($scope.badgeid); switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'New Arrival'; break; case 74: str = 'Recommend'; break; case 75: str = 'Best Seller'; break; } return str; }; $scope.pathChange = function() { var buildOtherReferral = function() {}; var path = { sendtag: $scope._viewRouteParams().sendtag, root_id: $scope._viewRouteParams().root_id, referral_id: $scope._viewRouteParams().referral_id, referral_type: 'category', sort: $scope.filterSortData, badge: $scope.filterbadge, }; var strHref = 'category-lists'; if (typeof path.sendtag !== 'undefined' && path.sendtag !== "") { strHref += '&sendtag=' + path.sendtag; } else { delete path.sendtag; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge; } else { delete path.badge; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; /*$rootScope.$on('$routeChangeSuccess', function(event, current, prev) {*/ if ($routeParams.referral_id) { $scope.FetchDisplayCategorylists($routeParams.referral_id); } else { $scope.FetchDisplayCategory(); } /*});*/ $scope.name_rootcat = false; $scope.getcatidname = function() {}; $scope.mkCarousel = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 992, settings: { slidesToShow: 1 } }, { breakpoint: 768, settings: { slidesToShow: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } }; return promise; });_ui_share_app.directive('productPageTypeOga', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOga'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._params = $routeParams.referral_id; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d, $scope).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.getRelation($scope._viewRouteParams().referral_id); $scope.filterbadge = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadge = function(input) { $scope.filterbadge = input; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterSortData = $scope._viewRouteParams().sort || 'product_category_sort_index_asc'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewType = 'grid'; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var j = { "badge_id_array_for_root": [18] }; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify(j) }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /*$scope.$watch('_params', function(newValue, oldValue) { if (newValue) { $scope.getcatidname(newValue); } });*/ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.diplayName = function() { var str = '', badgeTest = parseInt($scope.badgeid); switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'New Arrival'; break; case 74: str = 'Recommend'; break; case 75: str = 'Best Seller'; break; } return str; }; $scope.pathChange = function() { var buildOtherReferral = function() {}; var path = { sendtag: $scope._viewRouteParams().sendtag, root_id: $scope._viewRouteParams().root_id, referral_id: $scope._viewRouteParams().referral_id, referral_type: 'category', sort: $scope.filterSortData, badge: $scope.filterbadge, }; var strHref = 'category-lists'; if (typeof path.sendtag !== 'undefined' && path.sendtag !== "") { strHref += '&sendtag=' + path.sendtag; } else { delete path.sendtag; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge; } else { delete path.badge; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; /*$rootScope.$on('$routeChangeSuccess', function(event, current, prev) {*/ if ($routeParams.referral_id) { $scope.FetchDisplayCategorylists($routeParams.referral_id); } else { $scope.FetchDisplayCategory(); } /*});*/ $scope.name_rootcat = false; $scope.getcatidname = function() {}; $scope.mkCarousel = function(elem) { setTimeout(function() { var carousel = $(elem + '[data-id=' + $scope._key() + ']'); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: true, autoplay: true, autoplaySpeed: 4000, slidesToShow: 1, slidesToScroll: 1, infinite: true, speed: 600, responsive: [{ breakpoint: 1200, settings: { slidesToShow: 1, } }, { breakpoint: 992, settings: { slidesToShow: 1 } }, { breakpoint: 768, settings: { slidesToShow: 1 } }, { breakpoint: 480, settings: { slidesToShow: 1 } }] }).closest('section').addClass('active'); }, 1000); }; $scope._uniqueKey = ''; $scope._key = function() { if ($scope._uniqueKey === '') { $scope._uniqueKey = Math.floor((Math.random() * 9999) + 1000); return $scope._uniqueKey; } else { return $scope._uniqueKey; } }; $scope.slickGoLeft = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickPrev'); }, 100); }; $scope.slickGoRight = function() { setTimeout(function() { $('.recommend .-recommend[data-id="' + $scope._key() + '"]').slick('slickNext'); }, 100); }; /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } }; return promise; });_ui_share_app.directive('productPageTypeOh', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOh'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referralid: '@referralid', component: '@component', limitdata: '@limitdata', stylebutton: '@stylebutton', sortproduct: '@sortproduct', viewdata: '@viewdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._iconsize = (typeof $scope.iconsize !== 'undefined' && typeof $scope.iconsize !== '') ? $scope.iconsize : 30; $scope._iconback = (typeof $scope.iconback !== 'undefined' && typeof $scope.iconback !== '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = (typeof $scope.iconnext !== 'undefined' && typeof $scope.iconnext !== '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope._sortproduct = (typeof $scope.sortproduct !== 'undefined' && typeof $scope.sortproduct !== '') ? $scope.sortproduct : 'product_lastest_create'; $scope._viewdata = (typeof $scope.viewdata !== 'undefined' && typeof $scope.viewdata !== '') ? $scope.viewdata : 'grid'; $scope.tab = ""; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getReferralArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); /*var filter_json = { "badge_id_array":[16] } var dataSend = { 'txt_referral_type_id' : 11, 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) };*/ var dataSend = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_badge_id': 16, 'txt_parent_id': 0, 'txt_sortby': 'referral_sort_index_asc_time_desc', }; console.log('_getReferralArray dataSend_referral', dataSend); GAEAPI.get('referral/short_lists', dataSend, $scope).then(function(res) { /* referral/short_lists */ if (res.ok === 1) { $scope._dataArray = res.data.dataList; for (var i = 0; i < $scope._dataArray.length; i++) { $scope.getCategoryBannerArratID($scope._dataArray[i].referral_id); } if ($scope._viewRouteParams().referral_name != undefined) { $scope.intab($scope._viewRouteParams().referral_name); } else { if (res.data.dataList.length) { $scope.intab($scope._Get_Data_Array(res.data.dataList[0].referral_name, 0)); } } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope._getCategoryBannerArratId = []; $scope.getCategoryBannerArratID = function(id) { console.log("getCategory : ID : ", id); var dataSend = { 'txt_referral_id': id }; console.log('getCategory dataSend_referral', dataSend); GAEAPI.get('referral/id', dataSend, $scope).then(function(output) { console.log('getCategory output', output); if (output.ok === 1) { $scope._getCategoryBannerArratId[id] = output.data.referral_banner_array; console.log('getCategory ID : ', id, " $scope._getCategoryId ", $scope._getCategoryBannerArratId[id]); } }); }; $scope._Get_Data_Array = function(input, num) { var data = input; var array_data = data.split("-"); return array_data[num]; }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.intab = function(data) { console.log('intab : ', data); $scope.tab = data; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.mkCarousel = function(elem) { $('.product-page-type-oh').css('height', '0'); $('.product-page-type-oh').css('opacity', '0'); console.log("mkCarousel : ", $scope._slidestoshowlarge, $scope._slidestoshowmedium, $scope._slidestoshowsmall, $scope._slidestoshowextrasmall); setTimeout(function() { var carousel = $(elem); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: $scope._arrows, autoplay: true, centerMode: false, variableWidth: false, autoplaySpeed: 4000, slidesToShow: $scope._slidestoshowlarge, slidesToScroll: 1, infinite: true, speed: 600, /*prevArrow: '', nextArrow: '',*/ responsive: [{ breakpoint: 1200, settings: { slidesToShow: $scope._slidestoshowmedium, } }, { breakpoint: 991, settings: { slidesToShow: $scope._slidestoshowsmall, } }, { breakpoint: 767, settings: { slidesToShow: $scope._slidestoshowextrasmall, } }] }).closest('section').addClass('active'); $('.product-page-type-oh').css('height', 'auto'); $('.product-page-type-oh').css('opacity', '1'); }, 1000); }; $scope._getReferralArray($scope.badgeid); }; return promise; });_ui_share_app.directive('productPageTypeOm', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOm'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { referralid: '@referralid', component: '@component', limitdata: '@limitdata', stylebutton: '@stylebutton', sortproduct: '@sortproduct', viewdata: '@viewdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._iconsize = (typeof $scope.iconsize !== 'undefined' && typeof $scope.iconsize !== '') ? $scope.iconsize : 30; $scope._iconback = (typeof $scope.iconback !== 'undefined' && typeof $scope.iconback !== '') ? $scope.iconback : 'icnt_outline_backbig02_light@2x.png'; $scope._iconnext = (typeof $scope.iconnext !== 'undefined' && typeof $scope.iconnext !== '') ? $scope.iconnext : 'icnt_outline_nextbig02_light@2x.png'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope._sortproduct = (typeof $scope.sortproduct !== 'undefined' && typeof $scope.sortproduct !== '') ? $scope.sortproduct : 'product_lastest_create'; $scope._viewdata = (typeof $scope.viewdata !== 'undefined' && typeof $scope.viewdata !== '') ? $scope.viewdata : 'grid'; $scope.tab = ""; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getReferralArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); /*var filter_json = { "badge_id_array":[16] } var dataSend = { 'txt_referral_type_id' : 11, 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_filter_json': JSON.stringify(filter_json) };*/ var dataSend = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_badge_id': 16, 'txt_parent_id': 0, 'txt_sortby': 'referral_sort_index_asc_time_desc', }; console.log('_getReferralArray dataSend_referral', dataSend); GAEAPI.get('referral/short_lists', dataSend, $scope).then(function(res) { /* referral/short_lists */ if (res.ok === 1) { $scope._dataArray = res.data.dataList; for (var i = 0; i < $scope._dataArray.length; i++) { $scope.getCategoryBannerArratID($scope._dataArray[i].referral_id); } if ($scope._viewRouteParams().root_id != undefined) { $scope.intab($scope._viewRouteParams().referral_name); } else { if (res.data.dataList.length) { $scope.intab('all', 0); /*$scope.intab(res.data.dataList[0].referral_name, 0);*/ } } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope._getCategoryBannerArratId = []; $scope.getCategoryBannerArratID = function(id) { console.log("getCategory : ID : ", id); var dataSend = { 'txt_referral_id': id }; console.log('getCategory dataSend_referral', dataSend); GAEAPI.get('referral/id', dataSend, $scope).then(function(output) { console.log('getCategory output', output); if (output.ok === 1) { $scope._getCategoryBannerArratId[id] = output.data.referral_banner_array; console.log('getCategory ID : ', id, " $scope._getCategoryId ", $scope._getCategoryBannerArratId[id]); } }); }; $scope._Get_Data_Array = function(input, num) { var data = input; var array_data = data.split("-"); return array_data[num]; }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.intab = function(data) { console.log('intab : ', data); $scope.tab = data; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.getHeight = function() { return ($(window).width() > 767) ? 190 : 100; }; $scope._viewRouteParams_move_to = function(id) { var height = $scope.getHeight(); $timeout(function() { $('html, body').animate({ scrollTop: $("div[id='" + id + "']").offset().top - height }, 200); }, 500); }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope.mkCarousel = function(elem) { $('.product-page-type-oh').css('height', '0'); $('.product-page-type-oh').css('opacity', '0'); console.log("mkCarousel : ", $scope._slidestoshowlarge, $scope._slidestoshowmedium, $scope._slidestoshowsmall, $scope._slidestoshowextrasmall); setTimeout(function() { var carousel = $(elem); var is_dark; carousel.not('.slick-initialized').slick({ dots: true, arrows: $scope._arrows, autoplay: true, centerMode: false, variableWidth: false, autoplaySpeed: 4000, slidesToShow: $scope._slidestoshowlarge, slidesToScroll: 1, infinite: true, speed: 600, /*prevArrow: '', nextArrow: '',*/ responsive: [{ breakpoint: 1200, settings: { slidesToShow: $scope._slidestoshowmedium, } }, { breakpoint: 991, settings: { slidesToShow: $scope._slidestoshowsmall, } }, { breakpoint: 767, settings: { slidesToShow: $scope._slidestoshowextrasmall, } }] }).closest('section').addClass('active'); $('.product-page-type-oh').css('height', 'auto'); $('.product-page-type-oh').css('opacity', '1'); }, 1000); }; $scope._data_referral_map = []; $scope._data_referral_map_all = []; $scope._get_referral_map = function() { $scope._data_referral_map = []; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', dataSend, $scope).then(function(res) { if (res.ok === 1 && res.data.length) { $scope._data_referral_map = res.data; console.log("_get_referral_map : _data_referral_map : ", res.data); for (var i = 0; i < $scope._data_referral_map.length; i++) { for (var j = 0; j < $scope._data_referral_map[i].referral_sub_array.length; j++) { $scope._data_referral_map_all.push($scope._data_referral_map[i].referral_sub_array[j]); } } console.log("_get_referral_map : _data_referral_map_all : ", $scope._data_referral_map_all); } }); }; $scope._get_referral_map(); $scope._getReferralArray($scope.badgeid); $(window).scroll(function() { // console.log("_data_referral_map_all : ", $scope._data_referral_map_all.length) for (var i = 0; i < $scope._data_referral_map_all.length; i++) { var idDiv = $("#scroll-" + $scope._data_referral_map_all[i].referral_id); var scrollTop = $(window).scrollTop(); var start = idDiv.offset().top; var area = idDiv.outerHeight(true); var height = ($(window).width() > 992) ? 200 : 115; /* console.log(" scrollTop referral_id-: ", $scope._data_referral_map_all[i].referral_id); console.log(" scrollTop-: ", scrollTop, " start : ", start, " C : ", start - height, " end : ", end, " C : ", (start + end) - height); */ if (start - height <= scrollTop && scrollTop <= (start + area) - height) { // console.log(" scrollTop referral_id-: ", $scope._data_referral_map_all[i].referral_id); $("[referral='" + $scope._data_referral_map_all[i].referral_id + "']").addClass('active'); var dataMore = $('ul.-secondary li').not(".--hidden"); // console.log(" scrollTop dataMore-: ", dataMore); var dataMoreS = []; dataMore.each(function() { var secondaryId = $(this).attr('secondary'); dataMoreS.push(parseInt(secondaryId)); }); /* console.log("dataMoreS : ", dataMoreS, $scope._data_referral_map_all[i].referral_id); console.log("dataMoreS : ", dataMoreS.indexOf(parseInt($scope._data_referral_map_all[i].referral_id))); */ if (dataMoreS.indexOf(parseInt($scope._data_referral_map_all[i].referral_id)) != -1) { $(".-more button").addClass('active'); } else { $(".-more button").removeClass('active'); } } else { $("[referral='" + $scope._data_referral_map_all[i].referral_id + "']").removeClass('active'); } } }); }; return promise; });// _ui_share_app.filter('productPriceFilter', function() { // return function(items, inputConfig) { // var filtered = []; // var min = parseInt(inputConfig.min); // var max = parseInt(inputConfig.max); // angular.forEach(items, function(item) { // if (parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { // filtered.push(item); // } // }); // return filtered; // }; // }); _ui_share_app.directive('productPageTypeOo', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productPageTypeOo'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_price_desc'; $scope.changeFilterSortData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { /*var id = parseInt(v); var test = $scope.viewRouteParams().badge.indexOf(parseInt(v)) !== -1; if(test){ switch(id){ case 72: $scope.filter_new = true; break; case 74: $scope.filter_rec = true; break; case 75: $scope.filter_best = true; break; case 16: $scope.filter_fea = true; break; } } return test;*/ }; $scope.doFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } /* check sort */ // if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { // var refOArray = $routeParams.referral_array.split(','); // if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { // json_filter.referral_id_array_in = refOArray; // } else { // json_filter.referral_id_array_in = [refOArray]; // } // } console.log("json_filter.referral_id_array_in :" , json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'brand-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("brand-lists&", "brand-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); if($(window).height() > 595){ $('.erere').css('min-height',(($(window).height() - 145)+'px')); // alert($(window).height() - 145); } angular.element($window).bind('scroll', function() { var curPos = ($(document).scrollTop()); var properHeight = ($('.erere').height()); console.debug("Cur pos", curPos, properHeight); if($(window).width() > 991){ if ((curPos + ($(window).height() - 145)) > properHeight ) { if ((properHeight - curPos) <= ($(window).height() - 145)) { if(properHeight - ($(window).height() - 145) < 0){ document.getElementsByClassName('testrewq')[0].style.top = "0px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = "0px"; }else{ document.getElementsByClassName('testrewq')[0].style.top = (properHeight - ($(window).height() - 145)) + "px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = (properHeight - ($(window).height() - 145)) + "px"; } } else { document.getElementsByClassName('testrewq')[0].style.top = "auto"; } angular.element('.testrewq').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { document.getElementsByClassName('testrewq')[0].style.top = "auto"; angular.element('.testrewq').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }else{ angular.element('.testrewq').removeClass('unactive'); } }); }; return promise; });// _ui_share_app.filter('productPriceFilter', function() { // return function(items, inputConfig) { // var filtered = []; // var min = parseInt(inputConfig.min); // var max = parseInt(inputConfig.max); // angular.forEach(items, function(item) { // if (parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { // filtered.push(item); // } // }); // return filtered; // }; // }); _ui_share_app.directive('productPageTypeOp', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productPageTypeOp'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_price_desc'; $scope.changeFilterSortData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { /*var id = parseInt(v); var test = $scope.viewRouteParams().badge.indexOf(parseInt(v)) !== -1; if(test){ switch(id){ case 72: $scope.filter_new = true; break; case 74: $scope.filter_rec = true; break; case 75: $scope.filter_best = true; break; case 16: $scope.filter_fea = true; break; } } return test;*/ }; $scope.doFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } /* check sort */ // if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { // var refOArray = $routeParams.referral_array.split(','); // if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { // json_filter.referral_id_array_in = refOArray; // } else { // json_filter.referral_id_array_in = [refOArray]; // } // } console.log("json_filter.referral_id_array_in :" , json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; $scope.displayBadgeIdByString_param = function(strBadge) { // alert(strBadge); var badge_set = strBadge.split(","); switch (parseInt(badge_set[1])) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Hot Product'; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'brand-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("brand-lists&", "brand-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); if($(window).height() > 595){ $('.erere').css('min-height',(($(window).height() - 145)+'px')); // alert($(window).height() - 145); } angular.element($window).bind('scroll', function() { var curPos = ($(document).scrollTop()); var properHeight = ($('.erere').height()); console.debug("Cur pos", curPos, properHeight); if($(window).width() > 991){ if ((curPos + ($(window).height() - 145)) > properHeight ) { if ((properHeight - curPos) <= ($(window).height() - 145)) { if(properHeight - ($(window).height() - 145) < 0){ document.getElementsByClassName('testrewq')[0].style.top = "0px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = "0px"; }else{ document.getElementsByClassName('testrewq')[0].style.top = (properHeight - ($(window).height() - 145)) + "px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = (properHeight - ($(window).height() - 145)) + "px"; } } else { document.getElementsByClassName('testrewq')[0].style.top = "auto"; } angular.element('.testrewq').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { document.getElementsByClassName('testrewq')[0].style.top = "auto"; angular.element('.testrewq').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }else{ angular.element('.testrewq').removeClass('unactive'); } }); }; return promise; });_ui_share_app.filter('productPriceFilter', function() { return function(items, inputConfig, inasa) { var filtered = []; var min = parseInt(inputConfig.min); var max = parseInt(inputConfig.max); angular.forEach(items, function(item) { if (parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { filtered.push(item); } }); return filtered; }; }); _ui_share_app.directive('productPageTypeOq', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productPageTypeOq'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type) { $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.getUrlBadgeId = function() { var badge_id = ""; var step = $scope.viewRouteParams().badge != "" && $scope.viewRouteParams().badge != "undefined" && $scope.viewRouteParams().badge != undefined; if (step) { var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: badge_id = "72" break; case 74: badge_id = "74" break; case 75: badge_id = "75" break; case 16: badge_id = "16" break; } } } return badge_id }; $scope.filterId = $scope.getUrlBadgeId(); $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.changeLeftFilterByRadio = function(badgeId) { $scope.filterId = badgeId; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { /*var id = parseInt(v); var test = $scope.viewRouteParams().badge.indexOf(parseInt(v)) !== -1; if(test){ switch(id){ case 72: $scope.filter_new = true; break; case 74: $scope.filter_rec = true; break; case 75: $scope.filter_best = true; break; case 16: $scope.filter_fea = true; break; } } return test;*/ }; $scope.doFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; $scope.data_catall = []; $scope.getDatacatall = function() { if ($scope.data_catall.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data_catall = e.data; } }); } }; $scope.getDatacatall(); /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } /* check sort */ // if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { // var refOArray = $routeParams.referral_array.split(','); // if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { // json_filter.referral_id_array_in = refOArray; // } else { // json_filter.referral_id_array_in = [refOArray]; // } // } console.log("json_filter.referral_id_array_in :", json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { // var buildBadge = function() { // var r = [18]; // if ($scope.filter_new) { // r.push(72); // } // if ($scope.filter_rec) { // r.push(74); // } // if ($scope.filter_best) { // r.push(75); // } // if ($scope.filter_fea) { // r.push(16); // } // return r; // }; var buildBadge = function() { var r = [18]; if ($scope.filterId != '') { r.push($scope.filterId); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); // if($(window).height() > 595){ // $('.erere').css('min-height',(($(window).height() - 145)+'px')); // // alert($(window).height() - 145); // } }; return promise; }); _ui_share_app.directive('productPageTypeOr', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productPageTypeOr'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().referral_id, }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ /* $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; */ /* Get data brand * @return array */ /* $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; */ /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.filterSortData = 'product_lastest_create'; $scope.getDataProduct = function() { var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 30, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { $scope.data_product_done = true; if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; // alert($scope.data_product.length); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } // $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); }; $scope.getDataProduct(); $scope.getDataCategoryParent(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeOy', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeOy'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', limit: '@limit', topbar: '@topbar', text: '@text', todetail: '@todetail', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._params = $routeParams.referral_id; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.getBadgeIdName = function(badge_id) { if (badge_id == '72') { return 'Flash Zone'; } else if (badge_id == '74') { return 'แจกเหรียญ'; } else if (badge_id == '75') { return 'แจกแต้ม'; } }; $scope.badge = $scope._viewRouteParams().badge; $scope.fetchTime = 1; $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getdataProductBadge($scope._viewRouteParams().badge); }, 300); }; $scope.dataRelation = []; $scope.getRelation = function(referral_id) { var d = { 'txt_referral_id': referral_id }; GAEAPI.get('referral/relation', d).then(function(e) { if (e.ok == 1) { $scope.dataRelation = e.data; } }); }; $scope.productArray = []; // $scope.dataProductBadge = []; $scope.all_page = true; $scope.getdataProductBadge = function(badge_id) { var option = {}; if (badge_id != undefined) { option.badge_id_array = [18, badge_id]; } if ($scope._viewRouteParams().sort != '' || typeof $scope._viewRouteParams().sort === 'undefined') { var d = { 'cur_page': $scope.fetchTime, 'per_page': 20, 'txt_sortby': $scope._viewRouteParams().sort, 'txt_filter_json': JSON.stringify(option) }; } else { var d = { 'cur_page': $scope.fetchTime, 'per_page': 20, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(option) }; } // alert(option); /* Fetch Data */ GAEAPI.get('product/lists', d, $scope).then(function(e) { if (e.ok === 1) { console.log("ldfklfkdlfdlfkdfkdfdfd :", e.data.dataList); if ($scope.productArray.length) { // $scope.productArray = e.data.dataList; var curData = $scope.productArray; $scope.productArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } else { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } console.log("Share Component Get", d, option, e); $scope.productState = { load: false, done: true }; }); }; $scope.$watch('badge', function(newValue, oldValue) { console.log("newValue,oldValue", newValue, oldValue); if (!newValue) return; if (newValue != 0) { // alert(newValue); $scope.getdataProductBadge(newValue); } }); $scope.getRelation($scope._viewRouteParams().referral_id); $scope.filterbadge = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadge = function(input) { $scope.filterbadge = input; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterBadgeData = $scope._viewRouteParams().badge || ''; $scope.changeFilterBadgeselect = function() { $scope.filterbadge = $scope.filterBadgeData; // alert($scope.filterbadge); // return; $timeout(function() { $scope.pathChange(); }, 300); }; $scope.filterSortData = $scope._viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewdata = $routeParams.view || 'grid'; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.viewTypeSet = function(view_type) { $timeout(function() { $scope.viewdata = view_type; $scope.pathChange(); }, 300); }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.productState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } $scope.$watch('_params', function(newValue, oldValue) { if (newValue) { $scope.getcatidname(newValue); } }); $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.diplayName = function() { var str = '', badgeTest = parseInt($scope.badgeid); switch (badgeTest) { case 16: str = 'Featured Product'; break; case 72: str = 'New Arrival'; break; case 74: str = 'Recommend'; break; case 75: str = 'Best Seller'; break; } return str; }; $scope.pathChange = function() { var buildOtherReferral = function() {}; var path = { sendtag: $scope._viewRouteParams().sendtag, root_id: $scope._viewRouteParams().root_id, referral_id: $scope._viewRouteParams().referral_id, referral_type: 'category', sort: $scope.filterSortData, view: $scope.viewdata, badge: $scope.filterbadge, }; var strHref = 'product-badge-list'; if (typeof path.sendtag !== 'undefined' && path.sendtag !== "") { strHref += '&sendtag=' + path.sendtag; } else { delete path.sendtag; } if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge; } else { delete path.badge; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.sort; } if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("product-badge-list&", "product-badge-list?"); } $location.url(strHref).replace(); $scope.$apply(); }; $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { if ($routeParams.referral_id) { $scope.FetchDisplayCategorylists($routeParams.referral_id); } else { $scope.FetchDisplayCategory(); } }); $scope.name_rootcat = false; $scope.getcatidname = function() {}; }; return promise; });_ui_share_app.filter('productPriceFilter', function() { return function(items, inputConfig, inasa) { var filtered = []; var min = parseInt(inputConfig.min); var max = parseInt(inputConfig.max); angular.forEach(items, function(item) { if (parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { filtered.push(item); } }); return filtered; }; }); _ui_share_app.directive('productPageTypeOz', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productPageTypeOz'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* consoleLog */ $scope.consoleLog = function(text, data) { console.log(text, data); }; /* consoleLog */ /* referral/map */ $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.dataArray = []; $scope.dataArrayState = { load: false, done: false }; $scope.getReferralId = function(referral_id, callback) { var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': referral_id }; $scope.consoleLog("getReferralId : dataSend : ", dataSend); GAEAPI.get('referral/map', dataSend, $scope).then(function(output) { $scope.consoleLog("getReferralId : output : ", output); var referral_data = output.data; callback(referral_data); }); } $scope.getReferralMap = function() { $scope.dataArrayState = $scope.StateData(true, false); var filter_json = {} var dataSend = { 'txt_referral_type_id': 11, 'cur_page': 1, 'per_page': 20, 'txt_filter_json': JSON.stringify(filter_json) }; $scope.consoleLog("getReferralMap : dataSend : ", dataSend); GAEAPI.get('referral/map', dataSend, $scope).then(function(output) { $scope.consoleLog("getReferralMap : output : ", output); if (output.ok == 1) { $scope.dataArray = output.data; for (var i = 0; $scope.dataArray.length > i; i++) { $scope.consoleLog("getReferralMap : dataArray i : ", i); $scope.consoleLog("getReferralMap : dataArray : ", $scope.dataArray[i]); $scope.getReferralId($scope.dataArray[i].referral_id, function(referral_data) { $scope.consoleLog("getReferralId : referral_data : ", referral_data); }); } } $scope.dataArrayState = $scope.StateData(false, true); }); }; $scope.getReferralMap(); /* referral/map */ /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $('#petmyModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '20'; $scope.changefilterPerPageData = function() { $('#petmyModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type) { $timeout(function() { $scope.viewType = view_type; $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ $('#petmyModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { /*var id = parseInt(v); var test = $scope.viewRouteParams().badge.indexOf(parseInt(v)) !== -1; if(test){ switch(id){ case 72: $scope.filter_new = true; break; case 74: $scope.filter_rec = true; break; case 75: $scope.filter_best = true; break; case 16: $scope.filter_fea = true; break; } } return test;*/ }; $scope.doFilterBy = function(isChecked, badgeId) { /*var id = parseInt(badgeId); switch(id){ case 72: $scope.filter_new = isChecked; break; case 74: $scope.filter_rec = isChecked; break; case 75: $scope.filter_best = isChecked; break; case 16: $scope.filter_fea = isChecked; break; }*/ }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#petmyModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } /* check sort */ // if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { // var refOArray = $routeParams.referral_array.split(','); // if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { // json_filter.referral_id_array_in = refOArray; // } else { // json_filter.referral_id_array_in = [refOArray]; // } // } console.log("json_filter.referral_id_array_in :", json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 20, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* type */ type: $scope.viewRouteParams().type, /* brand_name */ brand_name: $scope.viewRouteParams().brand_name, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.type !== 'undefined' && path.type !== "") { strHref += '&type=' + path.type; } else { delete path.type; } if (typeof path.brand_name !== 'undefined' && path.brand_name !== "") { strHref += '&brand_name=' + path.brand_name; } else { delete path.brand_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); }; return promise; }); _ui_share_app.directive('productPageTypeP', function ($rootScope, $routeParams, $location) { var templateName = 'productPageTypeP'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.navChange = function(path){ }; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; $scope._get_referral_id = $scope._viewRouteParams().referral_id || false; $scope._get_root_id = $scope._viewRouteParams().root_id || false; $scope.categoryThis = []; $scope.categoryThisParent = []; $scope.buildCatgegoryMobile = function(){ if($('select#menuSubSelect_1 option').length <= 0){ var t = setTimeout(function(){ clearTimeout(t); getReferralMap(); },300); } }; /* * get referral data * @params {referralId} * @params {parentId} a.k.a root_id * @return array */ $scope.getThisReferral = function(referralId, parentId){ GAEAPI.get('referral/id',{'txt_referral_id':referralId}).then(function(e){ if(e.ok == 1){ $scope.categoryThis = e.data; if(e.data.referral_parent_id != 0){ GAEAPI.get('referral/id',{'txt_referral_id': e.data.referral_parent_id}).then(function(res){ if(res.ok == 1){ $scope.categoryThisParent = res.data; } }); }; } }); }; /* * Watch get params to query referal data */ $scope.$watch('_get_referral_id', function(newValue, oldValue){ if(!newValue) return; $scope.getThisReferral(newValue,$scope._viewRouteParams().root_id); }); /* * Fetch Category * @params none * @return array */ $scope.categoryArray = []; $scope.categoryLoad = false; $scope.categoryDone = false; $scope.getReferral = function(){ $scope.categoryLoad = true; $scope.categoryDone = false; var d = { 'txt_referral_type_id':11, 'txt_sortby':'referral_name_a-z', 'txt_filter_json':JSON.stringify({'badge_id_array_for_root':[18]}) }; GAEAPI.get('referral/map',d,$scope).then(function(e){ if(e.ok == 1){ $scope.categoryArray = e.data; } $scope.categoryLoad = false; $scope.categoryDone = true; }); }; if(!$scope.categoryArray.length){ $scope.getReferral(); } $scope.buildCatgegoryMobile(); /* * Arrange : brand * @params {objectArray} * @return array */ $scope.brandArray = []; $scope.getBrandList = function(){ var d = { 'txt_referral_type_id':12, 'cur_page':1, 'per_page':50, 'txt_sortby':'referral_name_a-z' }; GAEAPI.get('referral/lists',d).then(function(e){ if(e.ok == 1 && e.data.dataList.length){ $scope.brandArray = e.data.dataList; } }); }; $scope.getBrandList(); /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = ""; $scope.productListSort = $scope._viewRouteParams().sort || ""; $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; $scope.loadTime = 1; $scope.loadNoMore = false; $scope.getProduct = function () { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; /* Check: Search */ if(typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== ""){ option.search = $scope._viewRouteParams().search; } /* Check: referral */ if(typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0){ option.referral_id_array = [$scope._viewRouteParams().referral_id]; } /* Check: badge */ if(typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != ""){ /* Check Badge from URL */ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit,function(i,k){ option.badge_id_array.push(i); }); } else if($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false){ /* Check Badge from component (multibadge) */ if($scope.badgeid.indexOf(',') == -1){ var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i,k){ var test = i.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push(i.trim()); } }); } else { /* Check Badge from component (1 badge) */ var test = $scope.badgeid.trim(); if(option.badge_id_array.indexOf(test) == -1){ /* check exist */ option.badge_id_array.push($scope.badgeid.trim()); } } } /* Check Filter_data (brand,price,other) */ if(typeof $scope._viewRouteParams().filter_data !== 'undefined' && typeof $scope._viewRouteParams().filter_data != ""){ var a = $scope._viewRouteParams().filter_data.split('|'); option.referral_id_array_in = []; for(var i = 0; i < a.length; i++){ var b = a[i].split('@'); if(b[0] == 'brand'){ /* Referral(brand) */ if(b[1].indexOf(',')!==-1){ var c = b[1].split(','); for(var ii in c){ /*console.log("Share Component Get All: filter_data : array", c[ii]);*/ option.referral_id_array_in.push(c[ii]); } } else { option.referral_id_array_in.push(b[1]); /*console.log("Share Component Get All: filter_data : single", b[1]);*/ } } if(b[0] == 'price'){ /* Price */ } } /*console.log("Share Component Get All: filter_data", a);*/ } /* Check: sort by */ var sortBy = 'product_lastest_create'; if(typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != ""){ var r = $scope._viewRouteParams().sort; switch(r){ case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var curPage = (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1; if($scope.loadTime > 1){ curPage = $scope.loadTime; } var dataSend = { 'cur_page': curPage, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 12, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1) { /*if(e.data.dataList.length > 0){ $scope.productArray = e.data.dataList; $scope.buildPaginationParameter(e.data); } */ if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { if(e.data.dataList.length){ var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } else if($scope.loadTime > 1 && !e.data.dataList.length){ $scope.loadNoMore = true; } } /*console.log("productArray", $scope.productArray);*/ if($("#feature-product").hasClass('hide')){ $('#feature-product').removeClass('hide'); } } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get All", dataSend, option, e); }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function (data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function (total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener (sortby) * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel){ var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } paramsObj.sort = sortbyModel; $timeout(function () { $scope.productListSort=sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; /** * select listener (item per page) * @params model (string) * @return event */ $scope.displayChange = function(e){ if(window.location.href.indexOf('category-lists') !== -1){ $location.path("/category-lists").search({'page':1,'per_page':e}); } else { $location.path("/all-products").search({'page':1,'per_page':e});; } }; $scope.buildFilterUrl = function(exceptionalKey){ var a = ''; angular.forEach($routeParams, function (item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i){ return parseInt(i) || false; }; $scope.printSelected = function(a){ if($routeParams.sort == a){ return " selected"; } return " "; }; $scope.checkColorConfig = function(){ return ($('config-color').length) ? true : false; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; /* when route change success => do something */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("pageChangedSuccess", current); if($scope.loadTime > 1){ $scope.loadTime = 1; } $scope.getProduct(); if(!$scope.categoryArray.length && !$scope.categoryLoad.length){ $scope.getReferral(); } $scope.buildCatgegoryMobile(); }); /* FIlter FORM */ $scope.viewType = 'grid'; $scope._filter = $scope._viewRouteParams().filter_data; $scope.filterBrandModel = []; $scope.filter_brand = []; $scope.$watch('_filter', function(newValue,oldValue){ if(!newValue) return; var a = newValue.split('|'); for(var i = 0; i < a.length; i++){ var b = a[i].split('@'); if(b[0] == 'brand'){ var c = b[1].split(','); for(var ii = 0; ii < c.length; ii++){ $scope.filter_brand.push(parseInt(c[ii])); } } console.log('filter_brand',$scope.filter_brand); } }); $scope.checkFilterBrand = function(val){ return ($scope.filter_brand.indexOf(parseInt(val)) !== -1) ? true : false; }; $scope.checkFilterBrandChange = function(val, isSelect){ }; /* Button to load more */ $scope.loadMore = function(){ $scope.loadTime = $scope.loadTime+1; $timeout(function(){ $scope.getProduct(); },200); }; }; return promise; }); _ui_share_app.filter('productPriceFilterMyhappy', function() { return function(items, inputConfig) { var filtered = []; var min = parseInt(inputConfig.min); var max = parseInt(inputConfig.max); angular.forEach(items, function(item) { if (parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { filtered.push(item); } }); return filtered; }; }); _ui_share_app.directive('productPageTypePa', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productPageTypePa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', imgcart: '@imgcart', name: '@name' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; $scope._param = $routeParams; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.getBadgeName = function(badgeid) { var badge_name = ""; if (badgeid == "72") { badge_name = "สินค้าใหม่"; } else if (badgeid == "74") { badge_name = "สินค้าลดล้างสต็อค"; } else if (badgeid == "75") { badge_name = "สินค้าขายดี"; } return badge_name; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $timeout(function() { $('#slider-rangetest').slider({ range: true, min: 0, max: 100000, step: 100, values: [0, 100000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); }, 300); /*// $scope.myvalue = ""; // $scope.set_price = function(index,index_set){ // var actor = index.split('-'); // $scope.rangeConfig.min = actor[0]; // $scope.rangeConfig.max = actor[1]; // };*/ $scope.brand_id_array = []; $scope.setfilterbrand = function(brand, index) { if (brand.isChecked[brand.referral_id]) { $scope.brand_id_array.push(brand.referral_id); $scope.rangeConfig.brand = $scope.brand_id_array; console.log("test_array_brand :", $scope.brand_id_array, $scope.rangeConfig.brand); } else { var toDel = $scope.brand_id_array.indexOf(brand.referral_id); console.log("test_array_brand :", $scope.brand_id_array, toDel); $scope.brand_id_array.splice(toDel, '1'); $scope.rangeConfig.brand = $scope.brand_id_array; console.log("test_array_brand :", $scope.brand_id_array, $scope.rangeConfig.brand); } }; $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); // $timeout(function() { $scope.productListOnSortChange(); // }, 200); }; $scope.doBrandCheck = function(id) { $scope.buildParamsBrand(); var refId = parseInt(id); // alert($scope.filter_brand); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandCheckTwo = function(id) { return (window.location.href.indexOf(id) !== -1) ? true : false; }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { // $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); // $timeout(function() { $scope.productListOnSortChange(); // }, 300); } }; $scope._get_referral_id = $scope._viewRouteParams().referral_id || false; $scope.tag_name = $scope._viewRouteParams().tagname || false; $scope._get_root_id = $scope._viewRouteParams().root_id || false; $scope.categoryThis = []; $scope.categoryThisParent = []; $scope.buildCatgegoryMobile = function() { if ($('select#menuSubSelect_1 option').length <= 0) { var t = setTimeout(function() { clearTimeout(t); getReferralMap(); }, 300); } }; $scope.productListSort = $scope._viewRouteParams().sort || "product_lastest_create"; $scope.tag_array = []; $scope.tag_arrayStatedone = false; $scope.tag_arrayStateload = true; $scope.loadNoMore1 = false; $scope.loadTime1 = 1; $scope.all_item1 = 0; $scope.set_loadmore1 = true; $scope.getTagarray = function(tag, curpage) { $scope.tag_arrayStatedone = false; $scope.tag_arrayStateload = true; var option_tag = { "tags": tag, }; $scope.productTagSort = $scope._viewRouteParams().sort || ""; var d = { 'cur_page': curpage, 'per_page': 12, 'txt_sortby': $scope.productTagSort /* , 'txt_filter_json': JSON.stringify(option_tag),*/ }; GAEAPI.get('product/lists', d, $scope).then(function(e) { if (e.ok === 1 && !$scope.tag_array.length) { $scope.tag_array = e.data.dataList; if ($scope.all_item1 <= $scope.tag_array.length) { $scope.set_loadmore1 = false; } } else { if (e.data.dataList.length) { var currentData = $scope.tag_array; $scope.tag_array = currentData.concat(e.data.dataList); $scope.all_item1 = e.data.total_rows; if ($scope.all_item1 <= $scope.tag_array.length) { $scope.set_loadmore1 = false; } } else if ($scope.loadTime1 > 1 && !e.data.dataList.length) { $scope.loadNoMore1 = true; } } $scope.tag_arrayStatedone = true; $scope.tag_arrayStateload = false; }); }; /* * get referral data * @params {referralId} * @params {parentId} a.k.a root_id * @return array */ console.log("referal_testparent : 1", $scope.categoryThisParent); $scope.getThisReferral = function(referralId, parentId) { GAEAPI.get('referral/id', { 'txt_referral_id': referralId }, $scope).then(function(e) { if (e.ok == 1) { $scope.categoryThis = e.data; if (e.data.referral_parent_id != 0) { GAEAPI.get('referral/id', { 'txt_referral_id': e.data.referral_parent_id }).then(function(res) { if (res.ok == 1) { $scope.categoryThisParent = res.data; console.log("referal_testparent : ", $scope.categoryThisParent); } }); }; } }); }; /* * Watch get params to query referal data */ $scope.$watch('_get_referral_id', function(newValue, oldValue) { if (!newValue) return; $scope.getThisReferral(newValue, $scope._viewRouteParams().root_id); }); $scope.$watch('tag_name', function(newValue, oldValue) { if (!newValue) {} else { $scope.getTagarray(newValue, $scope.loadTime1); } }); /* * Fetch Category * @params none * @return array */ $scope.categoryArray = []; $scope.categoryLoad = false; $scope.categoryDone = false; $scope.getReferral = function() { if (CUR_THEME.shop_id() == "646" && typeof window.referalMap !== 'undefined') { $scope.categoryLoad = false; $scope.categoryDone = true; $scope.categoryArray = window.referalMap.data; return; } $scope.categoryLoad = true; $scope.categoryDone = false; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok == 1) { $scope.categoryArray = e.data; } $scope.categoryLoad = false; $scope.categoryDone = true; }); }; if (!$scope.categoryArray.length) { $scope.getReferral(); } $scope.buildCatgegoryMobile(); /* * Arrange : brand * @params {objectArray} * @return array */ $scope.brandArray = []; $scope.getBrandList = function() { var d = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 50, 'txt_sortby': 'referral_name_a-z' }; GAEAPI.get('referral/lists', d, $scope).then(function(e) { if (e.ok == 1 && e.data.dataList.length) { $scope.brandArray = e.data.dataList; } }); }; $scope.getBrandList(); $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = ""; $scope.productListSort = $scope._viewRouteParams().sort || "product_oldest_create"; $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; $scope.categoryListsArray = []; $scope.getCategoryId = function(id) { $scope.categoryListsArray = []; var d = { 'txt_referral_id': id, }; GAEAPI.get('referral/id_map', d, $scope).then(function(e) { if (e.data.referral_sub_array.length) { $('.width100').addClass("active"); $('.width0').addClass("active"); $scope.categoryListsArray = e.data.referral_sub_array; } else { $scope.categoryListsArray = []; if ($('.width100').hasClass("active")) { $('.width100').removeClass("active"); } if ($('.width0').hasClass("active")) { $('.width0').removeClass("active"); } } }); }; $scope.loadTime = 1; $scope.all_item = 0; $scope.set_loadmore = true; $scope.loadNoMore = false; $scope.productArrayDone = false; $scope.getProduct = function() { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; /* Check: Search */ if (typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== "") { option.search = $scope._viewRouteParams().search; } /* Check: referral */ if (typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0) { option.referral_id_array = [$scope._viewRouteParams().referral_id]; $scope.getCategoryId($scope._viewRouteParams().referral_id); } if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { option.referral_id_array_in = refOArray; } else { option.referral_id_array_in = refOArray; } } /* Check: badge */ if (typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != "") { /* Check Badge from URL */ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit, function(i, k) { option.badge_id_array.push(i); }); } else if ($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false) { /* Check Badge from component (multibadge) */ if ($scope.badgeid.indexOf(',') == -1) { var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i, k) { var test = i.trim(); if (option.badge_id_array.indexOf(test) == -1) { /* check exist */ option.badge_id_array.push(i.trim()); } }); } else { /* Check Badge from component (1 badge) */ var test = $scope.badgeid.trim(); if (option.badge_id_array.indexOf(test) == -1) { /* check exist */ option.badge_id_array.push($scope.badgeid.trim()); } } } /* Check Filter_data (brand,price,other) */ if (typeof $scope._viewRouteParams().filter_data !== 'undefined' && typeof $scope._viewRouteParams().filter_data != "") { var a = $scope._viewRouteParams().filter_data.split('|'); option.referral_id_array_in = []; for (var i = 0; i < a.length; i++) { var b = a[i].split('@'); if (b[0] == 'brand') { /* Referral(brand) */ if (b[1].indexOf(',') !== -1) { var c = b[1].split(','); for (var ii in c) { /*console.log("Share Component Get All: filter_data : array", c[ii]);*/ option.referral_id_array_in.push(c[ii]); } } else { option.referral_id_array_in.push(b[1]); /*console.log("Share Component Get All: filter_data : single", b[1]);*/ } } if (b[0] == 'price') { /* Price */ } } /*console.log("Share Component Get All: filter_data", a);*/ } /* Check: sort by */ var sortBy = 'product_oldest_create'; if (typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != "") { var r = $scope._viewRouteParams().sort; switch (r) { case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var curPage = (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1; if ($scope.loadTime > 1) { curPage = $scope.loadTime; } var dataSend = { 'cur_page': curPage, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 12, 'txt_sortby': sortBy, /* 'txt_filter_json': JSON.stringify(option) */ }; /* Fetch Data */ var timerApi = 0; GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { timerApi = $timeout(function() { $timeout.cancel(timerApi); if (e.ok === 1) { $scope.productArrayDone = true; /*if(e.data.dataList.length > 0){ $scope.productArray = e.data.dataList; $scope.buildPaginationParameter(e.data); } */ if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; $scope.all_item = e.data.total_rows; console.log("sdjksiodjsds : 0", $scope.all_item, $scope.productArray); if ($scope.all_item <= $scope.productArray.length) { $scope.set_loadmore = false; } } else { if (e.data.dataList.length) { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); $scope.all_item = e.data.total_rows; console.log("sdjksiodjsds : 1", $scope.all_item, $scope.productArray); if ($scope.all_item <= $scope.productArray.length) { $scope.set_loadmore = false; } } else if ($scope.loadTime > 1 && !e.data.dataList.length) { $scope.loadNoMore = true; } } /*console.log("productArray", $scope.productArray);*/ if ($("#feature-product").hasClass('hide')) { $('#feature-product').removeClass('hide'); } } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get All", dataSend, option, e); }, 100); }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function(data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function(total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener (sortby) * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var path = { referral_array: $scope.filter_brand, }; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { otherParams += "&referral_type=" + $location.search().referral_type; paramsObj.referral_type = $location.search().referral_type; } if (typeof $location.search().referral_name != 'undefined' && $location.search().referral_name != "") { otherParams += "&referral_name=" + $location.search().referral_name; paramsObj.referral_name = $location.search().referral_name; } if (typeof $location.search().badge != 'undefined' && $location.search().badge != "") { otherParams += "&badge=" + $location.search().badge; paramsObj.badge = $location.search().badge; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { otherParams += '&referral_array=' + path.referral_array.join(",").toString(); paramsObj.referral_array = path.referral_array.join(",").toString(); } else { delete path.referral_array; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; // $scope.productArray = []; // $scope.productState.load = false; // $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 200); }; $scope.productListOnSortChange1 = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('category-lists') !== -1) ? '/category-lists' : '/all-products'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().tagname != 'undefined' && $location.search().tagname != "") { otherParams += "&tagname=" + $location.search().tagname; paramsObj.tagname = $location.search().tagname; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productArrayDone = false; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); // $scope.$apply(); }, 300); }; /** * select listener (item per page) * @params model (string) * @return event */ $scope.displayChange = function(e) { if (window.location.href.indexOf('category-lists') !== -1) { $location.path("/category-lists").search({ 'page': 1, 'per_page': e }); } else { $location.path("/all-products").search({ 'page': 1, 'per_page': e });; } }; $scope.buildFilterUrl = function(exceptionalKey) { var a = ''; angular.forEach($routeParams, function(item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i) { return parseInt(i) || false; }; $scope.printSelected = function(a) { if ($routeParams.sort == a) { return " selected"; } return " "; }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; $scope.buildParamsBrand = function() { if (typeof $scope._viewRouteParams().referral_array !== 'undefined' && $scope._viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope._viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope._viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope._viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope._viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); /* when route change success => do something */ $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.productArrayDone && $scope.productArray.length) { $scope.productArrayDone = false; $scope.productArray = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { console.log("pageChangedSuccess", current); if ($scope.loadTime > 1) { $scope.loadTime = 1; } if (!$scope.productArray.length) { $scope.getProduct(); } if (!$scope.categoryArray.length && !$scope.categoryLoad.length) { $scope.getReferral(); } $scope.buildCatgegoryMobile(); $timeout(function() { $scope.buildParamsBrand(); }, 200); }); /* FIlter FORM */ $scope.viewType = 'grid'; $scope._filter = $scope._viewRouteParams().filter_data; $scope.filterBrandModel = []; $scope.filter_brand = []; $scope.$watch('_filter', function(newValue, oldValue) { if (!newValue) return; var a = newValue.split('|'); for (var i = 0; i < a.length; i++) { var b = a[i].split('@'); if (b[0] == 'brand') { var c = b[1].split(','); for (var ii = 0; ii < c.length; ii++) { $scope.filter_brand.push(parseInt(c[ii])); } } console.log('filter_brand', $scope.filter_brand); } }); $scope.checkFilterBrand = function(val) { return ($scope.filter_brand.indexOf(parseInt(val)) !== -1) ? true : false; }; $scope.checkFilterBrandChange = function(val, isSelect) {}; /* Button to load more */ $scope.loadMore = function() { $scope.loadTime = $scope.loadTime + 1; $timeout(function() { $scope.getProduct(); }, 200); }; $scope.loadMore1 = function() { $scope.loadTime1 = $scope.loadTime1 + 1; $timeout(function() { $scope.getTagarray($scope.tag_name, $scope.loadTime1); }, 200); }; /* $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.productArrayDone && $scope.productArray.length) { $scope.productArrayDone = false; $scope.productArray = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.productArrayDone && !$scope.productArray.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); */ $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel, '1'); console.log("test_array :", $scope.invited); } }; }; return promise; });_ui_share_app.directive('productPageTypePbs', function($rootScope, $routeParams) { var templateName = 'productPageTypePbs'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', sort: '@sort', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.stringToInt = function(string) { return parseInt(string); }; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypePbs : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(load, done) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : load : ", load); _self.consoleLog("getData : done : ", done); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: load, done: done }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 20, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.state = ""; $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypePge', function($rootScope, $routeParams) { var templateName = 'productPageTypePge'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', sort: '@sort', cardgrid: '@cardgrid', cardlist: '@cardlist', viewdata: '@viewdata', styletextgrid: '@styletextgrid', stylebuttongrid: '@stylebuttongrid', imgcartgrid: '@imgcartgrid', styletextlist: '@styletextlist', stylebuttonlist: '@stylebuttonlist', imgcartlist: '@imgcartlist', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypePge : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypePh', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypePh'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', referralid: '@referralid', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sortproduct: '@sort', limitdata: '@limitdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope._sortproduct = (typeof $scope.sortproduct !== 'undefined' && typeof $scope.sortproduct !== '') ? $scope.sortproduct : 'product_lastest_create'; $scope._viewdata = (typeof $scope.viewdata !== 'undefined' && typeof $scope.viewdata !== '') ? $scope.viewdata : 'grid'; $scope.tab = ""; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': id, }; console.log('dataSend_referral', dataSend); GAEAPI.get('referral/map', dataSend, $scope).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope._viewRouteParams_move_to(); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope._Get_Data_Array = function(input, num) { var data = input; var array_data = data.split("-"); return array_data[num]; }; $scope.getHeight = function() { return ($(window).width() > 767) ? 125 : 65; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._viewRouteParams_move_to = function() { var height = $scope.getHeight(); if ($scope._viewRouteParams().section != "undefined" && $scope._viewRouteParams().section != undefined) { $timeout(function() { $('html, body').animate({ scrollTop: $("div[id='" + $scope._viewRouteParams().section + "']").offset().top - height }, 200); }, 1000); } }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.intab = function(data) { console.log('intab : ', data); $scope.tab = data; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope._getProductArray($scope.referralid); }; return promise; });_ui_share_app.directive('productPageTypePhonda', function($rootScope, $routeParams, $location) { var templateComponent = 'productPageTypePhonda'; var templateUrl = _ui_share_host + templateComponent + '/' + templateComponent + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', type: '@type', home: '@home', btnstyle: '@btnstyle', moretext : '@moretext', loadingtext: '@loadingtext', limitproduct: '@limitproduct', categorytext : '@categorytext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templateUrl; promise.transclude = { 'one': '?one', 'two': '?two', 'three': '?three', }; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope._component = { name: "productPageTypePhonda", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; $scope._component_type = _ui_share_host + $scope._component.name + "/type/"; $scope._module = _ui_share_host + $scope._component.name + "/module/"; $scope._class = ($scope.type != undefined && $scope.type != "") ? $scope.type : "default"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._type = $scope._component_type + $scope._class + ".html"; $scope._home = ($scope.home != undefined && $scope.home != "") ? $scope.home : "หน้าแรก"; $scope._categorytext = ($scope.categorytext != undefined && $scope.categorytext != "") ? $scope.categorytext : "สินค้า"; $scope._limitproduct = ($scope.limitproduct != undefined && $scope.limitproduct != "") ? parseInt($scope.limitproduct) : 1; $scope._moretext = ($scope.moretext != undefined && $scope.moretext != "") ? $scope.moretext : "More"; $scope._loadingtext = ($scope.loadingtext != undefined && $scope.loadingtext != "") ? $scope.loadingtext : "Loading..."; $scope._btnstyle = ($scope.btnstyle != undefined && $scope.btnstyle != "") ? $scope.btnstyle : "filled_button_small"; /* scope */ $scope.params = { root_id : false, referral_id : false, } $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, getRouteState: function(params, callback) { var _self = this; var param = { root_id: (params.root_id != undefined && params.root_id != '') ? true : false, referral_id: (params.referral_id != undefined && params.referral_id != '') ? true : false, badge_id: (params.badge_id != undefined && params.badge_id != '') ? true : false, } $scope.params.root_id = (param.root_id)?params.root_id:param.root_id; $scope.params.referral_id = (param.referral_id)?params.referral_id:param.referral_id; _self.consoleLog("getRouteState", "param", param); var state = "main_category" if (param.root_id && param.referral_id) { _self.consoleLog("getRouteState", "param", param); state = "sub_category" } else if (param.badge_id) { state = "product_badge" } callback(state); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, getProductDealId: function(product, callback) { var _self = this; product.product_id = (product.product_deal_id != "0") ? product.product_deal_id : product.product_id; _self.consoleLog("getProductDealId", "product", product); callback(product); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.getSort = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, sortProductApi: function(sort_product) { var _self = this; $scope.data_sort.sort_product = sort_product; _self.callApi($scope.data_sort); }, sortBadgeApi: function(badge_id) { var _self = this; $scope.data_sort.sort_badge = badge_id; _self.callApi($scope.data_sort); }, callApi: function(data_sort) { var _self = this; if (!data_sort.sort) { data_sort.sort = true; _self.getApi(function(res_sort, res_txt_sortby, res_sort_badge) { data_sort.sort = res_sort; if (data_sort.sort_product != res_txt_sortby || data_sort.sort_badge != res_sort_badge) { _self.callApi(data_sort); } }); } }, getApi: function(callback) { $scope.getData().getRouteParams(function(_self, params, state) { _self.getRouteState(params, function(res_state) { if (res_state == "main_category") { $scope.data_api.product.ok = false; $scope.data_api.load_more.cur_page = 1; $scope.data_api.load_more.total_rows = 0; $scope.data_api.product.data_array_state = state; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = {}; var sort_badge = $scope.data_sort.sort_badge; if (sort_badge != '') { var badge_id_array = []; sort_badge = sort_badge; badge_id_array.push(sort_badge); txt_filter_json.badge_id_array = badge_id_array; } var data_send = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': $scope.data_sort.sort_product, 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getProductDealId(item, function(res_product) { res_data.data_array[index] = res_product; _self.getNameUrl(res_data.data_array[index].product_title, function(res_title) { res_data.data_array[index].product_title_url = res_title; }); }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; callback(false, res_data.data_send.txt_sortby, sort_badge); }); }); }); } else if (res_state == "sub_category") { $scope.data_api.product.ok = false; $scope.data_api.load_more.cur_page = 1; $scope.data_api.load_more.total_rows = 0; $scope.data_api.product.data_array_state = state; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = { 'referral_id_array_in': [params.referral_id] }; var sort_badge = $scope.data_sort.sort_badge; if (sort_badge != '') { var badge_id_array = []; sort_badge = sort_badge; badge_id_array.push(sort_badge); txt_filter_json.badge_id_array = badge_id_array; } var data_send = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': $scope.data_sort.sort_product, 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getProductDealId(item, function(res_product) { res_data.data_array[index] = res_product; _self.getNameUrl(res_data.data_array[index].product_title, function(res_title) { res_data.data_array[index].product_title_url = res_title; }); }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; callback(false, res_data.data_send.txt_sortby, sort_badge); }); }); }); } else if (res_state == "product_badge") { $scope.data_api.product.ok = false; $scope.data_api.load_more.cur_page = 1; $scope.data_api.load_more.total_rows = 0; $scope.data_api.product.data_array_state = state; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = {}; var sort_badge = $scope.data_sort.sort_badge; if (sort_badge != '') { var badge_id_array = []; sort_badge = sort_badge; badge_id_array.push(sort_badge); txt_filter_json.badge_id_array = badge_id_array; } var data_send = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': $scope.data_sort.sort_product, 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getProductDealId(item, function(res_product) { res_data.data_array[index] = res_product; _self.getNameUrl(res_data.data_array[index].product_title, function(res_title) { res_data.data_array[index].product_title_url = res_title; }); }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; callback(false, res_data.data_send.txt_sortby, sort_badge); }); }); }); } }); }); }, loadMore: function() { $scope.getData().getRouteParams(function(_self, params, state) { _self.getRouteState(params, function(res_state) { if (res_state == "main_category") { if (!$scope.data_api.load_more.load) { $scope.data_api.load_more.cur_page++; $scope.data_api.load_more.load = true; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = {}; var data_send = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': $scope.data_sort.sort_product, 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var oldData = res_data.data_array; res_data.data_array = oldData.concat(res_api.data.dataList); angular.forEach(res_data.data_array, function(item, index) { _self.getProductDealId(item, function(res_product) { res_data.data_array[index] = res_product; _self.getNameUrl(res_data.data_array[index].product_title, function(res_title) { res_data.data_array[index].product_title_url = res_title; }); }); }); _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; } else { $scope.data_api.load_more.cur_page--; } $scope.data_api.load_more.load = false; }); }); }); } } else if (res_state == "sub_category") { if (!$scope.data_api.load_more.load) { $scope.data_api.load_more.cur_page++; $scope.data_api.load_more.load = true; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = { 'referral_id_array_in': [params.referral_id] }; var data_send = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': $scope.data_sort.sort_product, 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var oldData = res_data.data_array; res_data.data_array = oldData.concat(res_api.data.dataList); angular.forEach(res_data.data_array, function(item, index) { _self.getProductDealId(item, function(res_product) { res_data.data_array[index] = res_product; _self.getNameUrl(res_data.data_array[index].product_title, function(res_title) { res_data.data_array[index].product_title_url = res_title; }); }); }); _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; } else { $scope.data_api.load_more.cur_page--; } $scope.data_api.load_more.load = false; }); }); }); } } else if (res_state == "product_badge") { if (!$scope.data_api.load_more.load) { $scope.data_api.load_more.cur_page++; $scope.data_api.load_more.load = true; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = {}; var sort_badge = $scope.data_sort.sort_badge; if (sort_badge != '') { var badge_id_array = []; sort_badge = sort_badge; badge_id_array.push(sort_badge); txt_filter_json.badge_id_array = badge_id_array; } var data_send = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': $scope.data_sort.sort_product, 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if (res_data.data_array.length < res_api.data.total_rows) { var oldData = res_data.data_array; res_data.data_array = oldData.concat(res_api.data.dataList); angular.forEach(res_data.data_array, function(item, index) { _self.getProductDealId(item, function(res_product) { res_data.data_array[index] = res_product; _self.getNameUrl(res_data.data_array[index].product_title, function(res_title) { res_data.data_array[index].product_title_url = res_title; }); }); }); _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; } else { $scope.data_api.load_more.cur_page--; } $scope.data_api.load_more.load = false; }); }); }); } } }); }); } } return getFunction; }; /* get api */ $scope.data_sort = { sort: false, sort_product: 'product_lastest_create', sort_badge: '' }; $scope.data_api = { type_name: "", shop_current: { data_send: {}, api: "shop/current", ok: false, data_array: [], data_array_state: { load: false, done: false } }, relation: { data_send: {}, api: "referral/relation", ok: false, data_array: [], data_array_state: { load: false, done: false } }, category: { data_send: {}, api: "referral/map", ok: false, data_array: [], data_array_state: { load: false, done: false } }, load_more: { load: false, cur_page: 1, per_page: $scope._limitproduct, total_rows: 0 }, product: { data_send: {}, api: "product/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.getData().getRouteParams(function(_self, params, state) { _self.getRouteState(params, function(res_state) { $scope.data_api.type_name = res_state; $scope.data_api.shop_current.data_array_state = state; _self.formatDataSend($scope.data_api.shop_current, function(res_data) { var data_send = {}; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); if (res_state == "main_category") { $scope.data_api.category.data_array_state = state; _self.formatDataSend($scope.data_api.category, function(res_data) { var data_send = { 'txt_referral_type_id': 11, 'txt_parent_id': 0, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); $scope.data_api.product.data_array_state = state; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = {}; var data_send = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': $scope.data_sort.sort_product, 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getProductDealId(item, function(res_product) { res_data.data_array[index] = res_product; _self.getNameUrl(res_data.data_array[index].product_title, function(res_title) { res_data.data_array[index].product_title_url = res_title; }); }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; }); }); }); } else if (res_state == "sub_category") { $scope.data_api.relation.data_array_state = state; _self.formatDataSend($scope.data_api.relation, function(res_data) { var data_send = { 'txt_referral_id': params.referral_id, }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); $scope.data_api.category.data_array_state = state; _self.formatDataSend($scope.data_api.category, function(res_data) { var data_send = { 'txt_referral_type_id': 11, 'txt_parent_id': 0, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data; res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); }); }); }); $scope.data_api.product.data_array_state = state; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = { 'referral_id_array_in': [params.referral_id] }; var data_send = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': $scope.data_sort.sort_product, 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getProductDealId(item, function(res_product) { res_data.data_array[index] = res_product; _self.getNameUrl(res_data.data_array[index].product_title, function(res_title) { res_data.data_array[index].product_title_url = res_title; }); }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; }); }); }); } else if (res_state == "product_badge") { _self.formatDataSend($scope.data_api.category, function(res_data) { res_data.ok = true; }); $scope.data_sort.sort_badge = params.badge_id; $scope.data_api.product.data_array_state = state; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = { 'badge_id_array': [params.badge_id] }; var data_send = { 'cur_page': $scope.data_api.load_more.cur_page, 'per_page': $scope.data_api.load_more.per_page, 'txt_sortby': $scope.data_sort.sort_product, 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; res_data.data_array = res_api.data.dataList; angular.forEach(res_data.data_array, function(item, index) { _self.getProductDealId(item, function(res_product) { res_data.data_array[index] = res_product; _self.getNameUrl(res_data.data_array[index].product_title, function(res_title) { res_data.data_array[index].product_title_url = res_title; }); }); }); res_data.data_array_state = res_state; _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.load_more.total_rows = res_api.data.total_rows; }); }); }); } }); }); /* get api */ }; return promise; });_ui_share_app.directive('productPageTypePhub', function($rootScope, $routeParams) { var templateName = 'productPageTypePhub'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { stylebutton: '@stylebutton', component: '@component', viewdata: '@viewdata', name: '@name', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeZaa : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypePkh', function($rootScope, $routeParams) { var templateName = 'productPageTypePkh'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', sort: '@sort', cardgrid: '@cardgrid', cardlist: '@cardlist', viewdata: '@viewdata', styletextgrid: '@styletextgrid', stylebuttongrid: '@stylebuttongrid', imgcartgrid: '@imgcartgrid', styletextlist: '@styletextlist', stylebuttonlist: '@stylebuttonlist', imgcartlist: '@imgcartlist', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypePkh : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypePm', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypePm'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', referralid: '@referralid', referralname: '@referralname', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sortproduct: '@sort', limitdata: '@limitdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._component = (typeof $scope.component !== 'undefined' && $scope.component !== '') ? $scope.component : 'null'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 6; $scope._stylebutton = (typeof $scope.stylebutton !== 'undefined' && typeof $scope.stylebutton !== '') ? $scope.stylebutton : 'filled_button_round_small'; $scope._sortproduct = (typeof $scope.sortproduct !== 'undefined' && typeof $scope.sortproduct !== '') ? $scope.sortproduct : 'product_lastest_create'; $scope._viewdata = (typeof $scope.viewdata !== 'undefined' && typeof $scope.viewdata !== '') ? $scope.viewdata : 'grid'; $scope.tab = ""; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': id, }; console.log('dataSend_referral', dataSend); GAEAPI.get('referral/map', dataSend, $scope).then(function(res) { if (res.ok === 1) { $scope._dataArray = res.data; $scope._viewRouteParams_move_to(); } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope._Get_Data_Array = function(input, num) { var data = input; var array_data = data.split("-"); return array_data[num]; }; $scope.getHeight = function() { return ($(window).width() > 767) ? 200 : 100; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._viewRouteParams_move_to = function() { var height = $scope.getHeight(); if ($scope._viewRouteParams().section != "undefined" && $scope._viewRouteParams().section != undefined) { $timeout(function() { $('html, body').animate({ scrollTop: $("div[id='" + $scope._viewRouteParams().section + "']").offset().top - height }, 200); }, 1000); } }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope.intab = function(data) { console.log('intab : ', data); $scope.tab = data; }; $scope.displayImage = function(image_url, prefix) { if (image_url != undefined) { return GAEAPI.getGaeImageUrl(image_url, prefix); } else { return ''; } } $scope._getProductArray($scope.referralid); }; return promise; });_ui_share_app.directive('productPageTypePmagic', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypePmagic'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', limitproduct: '@limitproduct', language: '@language', navigationhover: '@navigationhover', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = { name: "productPageTypePmagic", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._limitproduct = ($scope.limitproduct != undefined && $scope.limitproduct != "") ? parseInt($scope.limitproduct) : 1; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; $scope._navigationhover = ($scope.navigationhover != undefined && $scope.navigationhover != "") ? $scope.navigationhover : "primary"; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, getProductDealId: function(product, callback) { var _self = this; product.product_id = (product.product_deal_id != "0") ? product.product_deal_id : product.product_id; _self.consoleLog("getProductDealId", "product", product); callback(product); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, main: function() { var _self = this; } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.loadMore = function(index, referral_id) { if (!$scope.data_api.category.data_array[index].referral_load_more.load) { $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.category.data_array[index].product_cur_page++; $scope.data_api.category.data_array[index].referral_load_more = state; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = { 'referral_id_array': [referral_id] }; var data_send = { 'cur_page': $scope.data_api.category.data_array[index].product_cur_page, 'per_page': $scope.data_api.category.data_array[index].product_per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if ($scope.data_api.category.data_array[index].product_data_array.length < res_api.data.total_rows) { var oldData = $scope.data_api.category.data_array[index].product_data_array; $scope.data_api.category.data_array[index].product_data_array = oldData.concat(res_api.data.dataList); angular.forEach($scope.data_api.category.data_array[index].product_data_array, function(item, index_x) { _self.getNameUrl(item.product_title, function(res_title) { item.product_title_url = res_title; }); /* var images = []; angular.forEach(item.product_image,function(image,index_image){ if (image.image_app_cover_checked) { images.push(image) } }); item.product_image = images; */ }); _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.category.data_array[index].product_total_rows = res_api.data.total_rows; } else { $scope.data_api.category.data_array[index].product_cur_page--; } $scope.data_api.category.data_array[index].referral_load_more = res_state; }); }); }); }); } }; /* get api */ $scope.data_api = { shop_current: { data_send: {}, api: "shop/current", ok: false, data_array: [], data_array_state: { load: false, done: false } }, category: { data_send: {}, api: "referral/map", ok: false, data_array: [], data_array_state: { load: false, done: false } }, product: { data_send: {}, api: "product/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } }, load_more: { load: false, cur_page: 1, per_page: $scope._limitproduct, total_rows: 0 } }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.category.data_array_state = state; _self.formatDataSend($scope.data_api.category, function(res_data) { var data_send = { 'txt_referral_type_id': 11, 'txt_parent_id': 0, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { var res_api_array = { data: res_api.data.length, check: 0 }; angular.forEach(res_api.data, function(item, index) { item.index = index; item.referral_load_more = $scope.data_api.product.data_array_state; item.product_cur_page = $scope.data_api.load_more.cur_page; item.product_per_page = $scope.data_api.load_more.per_page; item.product_data_array_state = $scope.data_api.product.data_array_state; item.product_data_array = []; item.product_total_rows = 0; item.product_ok = false; _self.formatDataSend($scope.data_api.product, function(res_data_product) { var txt_filter_json = { 'referral_id_array': [item.referral_id], 'badge_id_array': [18] }; var data_send = { 'cur_page': item.product_cur_page, 'per_page': item.product_per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data_product.data_send = data_send; _self.dataSend(res_data_product.api, res_data_product.data_send, function(res_api_product, res_data_send) { _self.getApi(res_api_product, res_data_send, function(res_ok_product, res_api_product, res_state_product) { res_api_array.check += 1; if (res_ok && res_api_product.data.dataList.length > 0) { item.referral_load_more = res_state; item.product_ok = res_ok_product; item.product_data_array_state = res_state_product; angular.forEach(res_api_product.data.dataList, function(item, index) { _self.getNameUrl(res_api_product.data.dataList[index].product_title, function(res_title) { res_api_product.data.dataList[index].product_title_url = res_title; }); /* var images = []; angular.forEach(item.product_image,function(image,index_image){ if (image.image_app_cover_checked) { images.push(image) } }); item.product_image = images; */ }); item.product_data_array = res_api_product.data.dataList; item.product_total_rows = res_api_product.data.total_rows; res_data.ok = res_ok; res_data.data_array_state = res_state; res_data.data_array.push(item); res_data.data_array.sort(function(a, b) { return parseFloat(a.index) - parseFloat(b.index); }); } if (res_api_array.data == res_api_array.check) { res_data.data_array_state = res_state; } _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); if (res_api.data.length == 0) { res_data.data_array_state = res_state; } }); }); }); }); /* get api */ }; return promise; });_ui_share_app.directive('productPageTypePvono', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypePvono'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', limitproduct: '@limitproduct', language: '@language', navigationhover: '@navigationhover', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._component = { name: "productPageTypePvono", show: (window.location.hostname == "localhost") ? true : false }; $scope._imgPath = CUR_THEME.file_url() + "images/"; $scope._icnPath = CUR_THEME.file_url() + "../../assets/"; /* scope */ $scope._name = ($scope.name != undefined && $scope.name != "") ? $scope.name : "default"; $scope._limitproduct = ($scope.limitproduct != undefined && $scope.limitproduct != "") ? parseInt($scope.limitproduct) : 1; $scope._language = ($scope.language != undefined && $scope.language != "") ? (($scope.language == "en") ? "en" : "th") : "th"; $scope._navigationhover = ($scope.navigationhover != undefined && $scope.navigationhover != "") ? $scope.navigationhover : "primary"; /* scope */ $scope.getData = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, getRouteParams: function(callback) { var _self = this; var params = $routeParams; var state = _self.stateData(true, false); _self.consoleLog("getRouteParams", "params", params); callback(_self, params, state); }, formatDataSend: function(data, callback) { var _self = this; _self.consoleLog("formatDataSend", "data", data); callback(data); }, stateData: function(load, done) { var _self = this; var state = { load: load, done: done }; _self.consoleLog("stateData", "state", state); return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend", "api", api); _self.consoleLog("dataSend", "dataSend", dataSend); callback(api, dataSend); }, checkGetApi: function(resApi, callback) { var _self = this; var ok = false; if (resApi.ok == 1) { ok = true; } _self.consoleLog("checkGetApi", "ok", ok); callback(ok); }, getApi: function(api, dataSend, callback) { var _self = this; var state = _self.stateData(true, false); GAEAPI.get(api, dataSend, $scope).then(function(res_api) { _self.consoleLog("getApi", "res_api", res_api); _self.checkGetApi(res_api, function(res_ok) { _self.consoleLog("getApi", "res_ok", res_ok); state = _self.stateData(false, true); _self.consoleLog("checkGetApi", "state", state); callback(res_ok, res_api, state); }) }); }, getProductDealId: function(product, callback) { var _self = this; product.product_id = (product.product_deal_id != "0") ? product.product_deal_id : product.product_id; _self.consoleLog("getProductDealId", "product", product); callback(product); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); _self.consoleLog("getNameUrl", "name", name); callback(name); }, scrollTo: function(id) { if (id !== undefined) $('html,body').animate({ scrollTop: $("#" + id).offset().top - 130 }, 1000); }, main: function() { var _self = this; } } return getFunction; }; $scope.pages = function() { var getFunction = { consoleLog: function(function_name, data_name, data) { if ($scope._component.show) { console.log($scope._component.name, ' : ', function_name, ' : ', data_name, ' : ', data); } }, locationUrlReplace: function(page) { var _self = this; $location.url(page).replace(); }, pageUrl: function(page_name, id, name_url) { var _self = this; var page = page_name + "/" + id + "-" + name_url; _self.locationUrlReplace(page); } } return getFunction; }; $scope.loadMore = function(index, referral_id) { if (!$scope.data_api.category.data_array[index].referral_load_more.load) { $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.category.data_array[index].product_cur_page++; $scope.data_api.category.data_array[index].referral_load_more = state; _self.formatDataSend($scope.data_api.product, function(res_data) { var txt_filter_json = { 'referral_id_array': [referral_id] }; var data_send = { 'cur_page': $scope.data_api.category.data_array[index].product_cur_page, 'per_page': $scope.data_api.category.data_array[index].product_per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { res_data.ok = res_ok; if ($scope.data_api.category.data_array[index].product_data_array.length < res_api.data.total_rows) { var oldData = $scope.data_api.category.data_array[index].product_data_array; $scope.data_api.category.data_array[index].product_data_array = oldData.concat(res_api.data.dataList); angular.forEach($scope.data_api.category.data_array[index].product_data_array, function(item, index_x) { _self.getNameUrl(item.product_title, function(res_title) { item.product_title_url = res_title; }); var images = []; angular.forEach(item.product_image,function(image,index_image){ if (image.image_app_cover_checked) { images.push(image) } }); item.product_image = images; }); _self.consoleLog("getApiData", "res_data", res_data); $scope.data_api.category.data_array[index].product_total_rows = res_api.data.total_rows; } else { $scope.data_api.category.data_array[index].product_cur_page--; } $scope.data_api.category.data_array[index].referral_load_more = res_state; }); }); }); }); } }; /* get api */ $scope.data_api = { shop_current: { data_send: {}, api: "shop/current", ok: false, data_array: [], data_array_state: { load: false, done: false } }, category: { data_send: {}, api: "referral/map", ok: false, data_array: [], data_array_state: { load: false, done: false } }, product: { data_send: {}, api: "product/lists", ok: false, data_array: [], data_array_state: { load: false, done: false } }, load_more: { load: false, cur_page: 1, per_page: $scope._limitproduct, total_rows: 0 } }; $scope.getData().getRouteParams(function(_self, params, state) { $scope.data_api.category.data_array_state = state; _self.formatDataSend($scope.data_api.category, function(res_data) { var data_send = { 'txt_referral_type_id': 11, 'txt_parent_id': 0, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; res_data.data_send = data_send; _self.dataSend(res_data.api, res_data.data_send, function(res_api, res_data_send) { _self.getApi(res_api, res_data_send, function(res_ok, res_api, res_state) { var res_api_array = { data: res_api.data.length, check: 0 }; angular.forEach(res_api.data, function(item, index) { item.index = index; item.referral_load_more = $scope.data_api.product.data_array_state; item.product_cur_page = $scope.data_api.load_more.cur_page; item.product_per_page = $scope.data_api.load_more.per_page; item.product_data_array_state = $scope.data_api.product.data_array_state; item.product_data_array = []; item.product_total_rows = 0; item.product_ok = false; _self.formatDataSend($scope.data_api.product, function(res_data_product) { var txt_filter_json = { 'referral_id_array': [item.referral_id], 'badge_id_array': [18] }; var data_send = { 'cur_page': item.product_cur_page, 'per_page': item.product_per_page, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(txt_filter_json) }; res_data_product.data_send = data_send; _self.dataSend(res_data_product.api, res_data_product.data_send, function(res_api_product, res_data_send) { _self.getApi(res_api_product, res_data_send, function(res_ok_product, res_api_product, res_state_product) { res_api_array.check += 1; if (res_ok && res_api_product.data.dataList.length > 0) { item.referral_load_more = res_state; item.product_ok = res_ok_product; item.product_data_array_state = res_state_product; angular.forEach(res_api_product.data.dataList, function(item, index) { _self.getNameUrl(res_api_product.data.dataList[index].product_title, function(res_title) { res_api_product.data.dataList[index].product_title_url = res_title; }); var images = []; angular.forEach(item.product_image,function(image,index_image){ if (image.image_app_cover_checked) { images.push(image) } }); item.product_image = images; }); item.product_data_array = res_api_product.data.dataList; item.product_total_rows = res_api_product.data.total_rows; res_data.ok = res_ok; res_data.data_array_state = res_state; res_data.data_array.push(item); res_data.data_array.sort(function(a, b) { return parseFloat(a.index) - parseFloat(b.index); }); } if (res_api_array.data == res_api_array.check) { res_data.data_array_state = res_state; setTimeout(function() { _self.scrollTo(params.scroll_id); }, 1000); } _self.consoleLog("getApiData", "res_data", res_data); }); }); }); }); if (res_api.data.length == 0) { res_data.data_array_state = res_state; } }); }); }); }); /* get api */ }; return promise; });_ui_share_app.directive('productPageTypePwc', function($rootScope, $routeParams) { var templateName = 'productPageTypePwc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { stylebutton: '@stylebutton', component: '@component', viewdata: '@viewdata', name: '@name', sort: '@sort', min: '@min', max: '@max', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.$watch('min', function(newMin, oldMin) { $scope.newMin = parseInt(newMin); $scope.oldMin = parseInt(oldMin); }); $scope.$watch('max', function(newMax, oldMax) { $scope.newMax = parseInt(newMax); $scope.oldMax = parseInt(oldMax); }); $scope.stringToInt = function(string) { return parseInt(string); }; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypePwc : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 20, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypeR', function($rootScope, $routeParams) { var templateName = 'productPageTypeR'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', badgeid: '@badgeid', imgpath: '@imgpath', margin: '@margin', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ console.log("ydgfyhfgfdsdf", $scope.badgeid); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'product_oldest_create' }; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { console.log("Watch Referral", newValue); if (newValue != 0) { $scope.getProduct(newValue, false); } else if (newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue, true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if (isPageChange) { $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby': 'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function(isPageChange) { if (isPageChange) { $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; if ($scope.badgeid != null || $scope.badgeid != "") { option.badge_id_array = [18, $scope.badgeid]; } else { option.badge_id_array = [18]; } var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby': 'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); }); }; $scope.loadMore = function() { $('div#slider-range').html(''); if ($scope.fetchType == 1) { $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function() { if ($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem) { var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if (ObjectItem.referral_parent_id != 0) { str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeRb', function ($rootScope, $routeParams) { var templateName = 'productPageTypeRb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', badgeid: '@badgeid', imgpath: '@imgpath', img: '@img', text: '@text', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ console.log("badgeid",$scope.badgeid); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'product_oldest_create'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; if($scope.badgeid != null || $scope.badgeid != ""){ option.badge_id_array=[18,$scope.badgeid]; }else{ option.badge_id_array=[18]; } var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); /*$('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} });*/ }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeRc', function ($rootScope, $routeParams) { var templateName = 'productPageTypeRc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', badgeid: '@badgeid', imgpath: '@imgpath', img: '@img', text: '@text', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = { 'header_badge': '?headerBadge', }; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ console.log("badgeid",$scope.badgeid); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'product_oldest_create'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; if($scope.badgeid != null || $scope.badgeid != ""){ /*// var testuuu = ""+$scope.badgeid;*/ option.badge_id_array=[18,$scope.badgeid]; }else{ option.badge_id_array=[18]; } var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); /*$('div#slider-range').slider({ range: true, min: 0, max: 100, values: [75,300], slide: function(event, ui ) {} });*/ }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeS', function($rootScope, $routeParams) { var templateName = 'productPageTypeS'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', badgeid: '@badgeid', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.referral = $routeParams.category || $routeParams.brand || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ console.log("ydgfyhfgfdsdf", $scope.badgeid); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'product_oldest_create' }; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { console.log("Watch Referral", newValue); if (newValue != 0) { $scope.getProduct(newValue, false); } else if (newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue, true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if (isPageChange) { $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby': 'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function(isPageChange) { if (isPageChange) { $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; if ($scope.badgeid != null || $scope.badgeid != "") { /*// var testuuu = ""+$scope.badgeid;*/ option.badge_id_array = [18, $scope.badgeid]; } else { option.badge_id_array = [18]; } var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby': 'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); }); }; $scope.loadMore = function() { $('div#slider-range').html(''); if ($scope.fetchType == 1) { $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function() { if ($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem) { var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if (ObjectItem.referral_parent_id != 0) { str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productPageTypeSa', function($rootScope, $routeParams) { var templateName = 'productPageTypeSa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', badgeid: '@badgeid', imgpath: '@imgpath', iconcart: '@iconcart', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.referral = $routeParams.category || $routeParams.brand || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ console.log("ydgfyhfgfdsdf", $scope.badgeid); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'product_oldest_create' }; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function(newValue, oldValue) { console.log("Watch Referral", newValue); if (newValue != 0) { $scope.getProduct(newValue, false); } else if (newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue, true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if (isPageChange) { $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; option.referral_id_array = [ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby': 'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; $scope.getAllProduct = function(isPageChange) { if (isPageChange) { $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; if ($scope.badgeid != null || $scope.badgeid != "") { option.badge_id_array = [18, $scope.badgeid]; } else { option.badge_id_array = [18]; } var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby': 'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); }); }; $scope.loadMore = function() { $('div#slider-range').html(''); if ($scope.fetchType == 1) { $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function() { if ($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem) { var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if (ObjectItem.referral_parent_id != 0) { str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; $scope.pricefullState = function(price, compare_price, discount_id, discount_price, discount_percent) { var state = 0; if (discount_id != undefined) { state = 'not zero'; } else { if (compare_price != 0) { state = 'not zero'; } else { state = 'zero'; } } return state; } $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productPageTypeSb', function($rootScope, $routeParams) { var templateName = 'productPageTypeSb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.imgPath = CUR_THEME.file_url() + 'images/'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.showData = []; $scope.showDataState = { load: true, done: false }; $scope.getProductData = function(referral_id) { $scope.showDataState = $scope.StateData(true, false); var jsonFilter = { 'referral_id_array_in': [parseInt($scope._viewRouteParams().referral_id)], 'badge_id_array': [18] }; var dataSend = { 'cur_page': 1, 'per_page': 10, 'txt_sortby': 'product_title_a-z', 'txt_filter_json': JSON.stringify(jsonFilter) }; console.log("dataSend", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.showData = e.data.dataList; console.log("dataSend", $scope.showData); } $scope.showDataState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope.getProductData($scope._viewRouteParams().referral_id); $scope.pricefullState = function(price, compare_price, discount_id, discount_price, discount_percent) { var state = 0; if (discount_id != undefined) { state = 'not zero'; } else { if (compare_price != 0) { state = 'not zero'; } else { state = 'zero'; } } return state; } $scope.pricefull = function(price, compare_price, discount_id, discount_price, discount_percent) { var pricefull = 0; if (discount_id != undefined) { pricefull = price; } else { if (compare_price != 0) { pricefull = compare_price; } } return pricefull; } $scope.calculate = function(price, compare_price, discount_id, discount_price, discount_percent) { var calculate = 0; if (discount_id != undefined) { if (discount_price != 0 && discount_percent == 0) { calculate = price - discount_price; } else if (discount_percent != 0 && discount_price == 0) { calculate = price - ((discount_percent / 100) * price); } } else { calculate = price } return (calculate > 0) ? calculate : 0; } $scope.displayImage = function(image_url, prefix) { return (typeof image_url !== 'undefined') ? GAEAPI.getGaeImageUrl(image_url, prefix) : ''; } $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; }; return promise; });_ui_share_app.directive('productPageTypeSc', function($rootScope, $routeParams) { var templateName = 'productPageTypeSc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', badgeid: '@badgeid', limitdata: '@limitdata', sortby: '@sortby', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.component = "productPageTypeSc : "; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? parseInt($scope.limitdata) : 6; $scope._sortby = (typeof $scope.sortby !== 'undefined' && typeof $scope.sortby !== '') ? $scope.sortby : 'product_update_time_asc'; $scope.dataSet = [{ api: "product/lists", dataSend: {}, dataArray: [], dataSendState: { load: false, done: false } }]; $scope.getFunction = function() { var getFunction = { component: function(callback) { var component = $scope.component; callback(component); }, consoleLog: function(name, data) { var _self = this; _self.component(function(component) { /*console.log(component, name, data);*/ }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, momentUnix: function(callback) { var now = moment().unix(); callback(now); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); _self.consoleLog("stateData : loadIn : ", loadIn); _self.consoleLog("stateData : doneIn : ", doneIn); _self.consoleLog("stateData : ", "----------------------------------- stateData -----------------------------------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); _self.consoleLog("dataSend : api : ", api); _self.consoleLog("dataSend : dataSend : ", dataSend); _self.consoleLog("dataSend : ", "----------------------------------- dataSend -----------------------------------"); callback(api, dataSend); }, getApiOk: function(output, callback) { var _self = this; var output_ok = []; if (output.ok == 1) { output_ok = output; } _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); _self.consoleLog("getApiOk : output_ok : ", output_ok); _self.consoleLog("getApiOk : ", "----------------------------------- getApiOk -----------------------------------"); callback(output_ok); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getApi : api : ", api); _self.consoleLog("getApi : dataSend : ", dataSend); _self.consoleLog("getApi : output : ", output); _self.consoleLog("getApi : ", "----------------------------------- getApi -----------------------------------"); _self.getApiOk(output, function(output) { callback(output); }); }); }, main: function(badge_id_array_in) { var _self = this; $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(true, false); _self.momentUnix(function(now) { var badge_id_array_get_api = badge_id_array_in.split(","); var filter_json = { 'badge_id_array': badge_id_array_get_api, 'event_lifetime_enable': { from: now, } } $scope.dataSet[0].dataSend = { 'cur_page': 1, 'per_page': $scope._limitdata, 'txt_sortby': $scope._sortby, 'txt_filter_json': JSON.stringify(filter_json) }; _self.dataSend($scope.dataSet[0].api, $scope.dataSet[0].dataSend, function(api, dataSend) { _self.getApi(api, dataSend, function(output) { _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); _self.consoleLog("getRouteParams : dataSend : getApi : ", output); _self.consoleLog("getRouteParams : dataSend : getApi : ", "----------------------------------- getApi -----------------------------------"); $scope.dataSet[0].dataArray = output.data.dataList; setTimeout(function() { $scope.dataSet[0].dataSendState = $scope.getFunction().stateData(false, true); }, 1000); }); }); }); } } return getFunction; }; $scope.getFunction().main($scope.badgeid); }; return promise; });_ui_share_app.directive('productPageTypeStyle', function($rootScope, $routeParams) { var templateName = 'productPageTypeStyle'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeStyle : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 15, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.data_api = { shop_current: { data_send: {}, api: "shop/current", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.getData().getRouteParams(function(params) { var dataSend = {}; $scope.getData().dataSend($scope.data_api.shop_current.api, $scope.data_api.shop_current.data_send, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.data_api.shop_current.data_array = output.data; }); }); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypeT', function($rootScope, $routeParams) { var templateName = 'productPageTypeT'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', coloractive: '@coloractive', stilebutton: '@stilebutton', textbutton: '@textbutton', textheader: '@textheader', bordercolor: '@bordercolor', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.ref_id = $routeParams.referral_id; $scope.product_status = $routeParams.product; $scope.brand_array = $routeParams.brand_id; $scope.ReferralDisplayArray = []; $scope.FetchDisplayCategory = function(ref_id) { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', }; var dummyArray = []; if (typeof $scope.ref_id !== 'undefined') { d["txt_parent_id"] = $scope.ref_id; } GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; for(var i = 0; i < e.data.length; i++){ dummyArray.push(parseInt(e.data[i].referral_id)); } } console.log('ref_id', $scope.ref_id); console.log('ReferralDisplayArray', $scope.ReferralDisplayArray); console.log('referral_sub_array', $scope.ReferralDisplayArray[0].referral_id); console.log('referral_sub_array : dummyArray', dummyArray); $scope.getArrivalList(dummyArray); }); }; $scope.$watch('ref_id', function(newValue) { if (!newValue || newValue == 0) { return $scope.FetchDisplayCategory(); } $scope.FetchDisplayCategory(newValue); }); $scope.$watch('brand_array', function(newValue) { if (!newValue || newValue == 0) { return $scope.getproductBrandList($scope.brand_array); } $scope.getproductBrandList(newValue); }); $scope.ArrivalList = []; $scope.getArrivalList = function(childReferralArray) { var txt_filter_json = { /*'badge_id_array': [18],*/ 'referral_id_array_in': childReferralArray, } var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(res) { if (res.ok == 1) { $scope.ArrivalList = res.data.dataList; $scope.count_array = 0; for(var i = 0; i < res.data.dataList.length; i++){ if($scope.brand_array == res.data.dataList[i].product_referral_display.brand[0].referral_id){ $scope.count_array++; } } } console.log("dummyArray: ArrivalList", $scope.ArrivalList); }); }; /*$scope.getArrivalList();*/ $scope.productBrabdList = []; $scope.getproductBrandList = function(brand_id) { $scope.productBrabdList = []; var txt_filter_json_1 = { 'referral_id_array': [brand_id], } var data_test = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(txt_filter_json_1) }; GAEAPI.get('product/lists', data_test, $scope).then(function(res) { if (res.ok == 1) { $scope.productBrabdList = res.data.dataList; console.log("dummyArray: productBrabdList", $scope.productBrabdList); } }); }; }; return promise; }); _ui_share_app.directive('productPageTypeU', function ($rootScope, $routeParams) { var templateName = 'productPageTypeU'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', badgeid: '@badgeid', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.referral = $routeParams.category || $routeParams.brand || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ console.log("ydgfyhfgfdsdf",$scope.badgeid); $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'product_oldest_create'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { console.log("Watch Referral",newValue); if (newValue != 0) { $scope.getProduct(newValue,false); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(false); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; /* Route Change */ $rootScope.$on('$routeChangeSuccess', function (event, current, prev) { console.log("Watch Referral: routeChangeSuccess", current.params.referral_id); var newValue = parseInt($routeParams.referral_id) || 0; $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 12; if (newValue > 0) { console.log("Watch Referral: Case 1", newValue); $scope.getProduct(newValue,true); } else { console.log("Watch Referral: Case 2", newValue); $scope.getAllProduct(true); } }); /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id, isPageChange) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; console.log("Watch Referral: error get ref"); return; } if(isPageChange){ $scope.productArray = []; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function (isPageChange) { if(isPageChange){ $scope.productArray = []; } $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; if($scope.badgeid != null || $scope.badgeid != ""){ option.badge_id_array=[18,$scope.badgeid]; }else{ option.badge_id_array=[18]; } var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': $scope.fetchLimit, 'txt_sortby':'product_oldest_create', 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option); }); }; $scope.loadMore = function(){ $('div#slider-range').html(''); if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* Filter */ $scope.filterIsActive = 0; $scope.toggleFilterPanel = function(){ if($scope.filterIsActive == 0) $scope.filterIsActive = 1; else $scope.filterIsActive = 0; return; }; /* Category Head */ $scope._buildLinkByReferral = function(ObjectItem){ var str = '#/product-template?id=9' + '&referral_id=' + ObjectItem.referral_id; if(ObjectItem.referral_parent_id != 0){ str += "&root_id=" + ObjectItem.referral_parent_id; } else { str += "&root_id=" + ObjectItem.referral_id; } str += '&referral_type=category'; str += '&referral_name=' + ObjectItem.referral_name; return str || '#/home'; }; $scope.checkSeo = function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeV', function($rootScope, $routeParams) { var templateName = 'productPageTypeV'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', referralid: '@referralid' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.productData = []; $scope._productData = function(id) { var txt_filter_json = { 'referral_id_array': [id] }; var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { $scope.productData = e.data.dataList; console.log("_productData ", $scope.productData); } }); }; $scope._productData($scope.referralid); }; return promise; });_ui_share_app.directive('productPageTypeVono', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeVono'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', home: '@home', category: '@category', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { var show = (window.location.hostname == "localhost") ? true : false; if (show) { console.log('productPageTypeVono : ', name, data); } }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.state = ""; $scope.cover_top = ($scope.category != undefined && $scope.category != "") ? $scope.category : "category-lists"; $scope.totalRows = 0; $scope.totalRowsState = $scope.getData().stateData(false, false); $scope.dataRelation = []; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.getData().consoleLog('referral/id : res : ', output); $scope.cover_top = output.data.referral_name; }); }); var txt_filter_json = {}; var dataSend = { 'txt_referral_id': params.referral_id, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('referral/id_map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.totalRows = output.data.referral_product_amount; $scope.totalRowsState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; $scope.totalRowsState = $scope.getData().stateData(false, true); }); }); var txt_filter_json = {}; var dataSend = { 'txt_referral_id': params.referral_id, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('referral/id_map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.totalRows = output.data.referral_product_amount; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.state = ""; $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { $scope.badgeData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData, price: $scope.price }; var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('productPageTypeVonoP', function($rootScope, $routeParams) { var templateName = 'productPageTypeVonoP'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', sort: '@sort', stylebutton: '@stylebutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.stringToInt = function(string) { return parseInt(string); }; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { var show = (window.location.hostname == "localhost") ? true : false; if (show) { console.log('productPageTypeVonoP : ', name, data); } }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, getNameUrl: function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); callback(name); }, stateData: function(load, done) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : load : ", load); _self.consoleLog("getData : done : ", done); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: load, done: done }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 20, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; angular.forEach($scope.dataArray, function(item, index) { $scope.getData().getNameUrl($scope.dataArray[index].product_title, function(res_title) { $scope.dataArray[index].product_title_url = res_title; }); }); $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; angular.forEach($scope.dataArray, function(item, index) { $scope.getData().getNameUrl($scope.dataArray[index].product_title, function(res_title) { $scope.dataArray[index].product_title_url = res_title; }); }); $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.state = ""; $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); angular.forEach($scope.dataArray, function(item, index) { $scope.getData().getNameUrl($scope.dataArray[index].product_title, function(res_title) { $scope.dataArray[index].product_title_url = res_title; }); }); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); angular.forEach($scope.dataArray, function(item, index) { $scope.getData().getNameUrl($scope.dataArray[index].product_title, function(res_title) { $scope.dataArray[index].product_title_url = res_title; }); }); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; } else { $scope.state = ""; } }); } }; }; return promise; }); _ui_share_app.directive('productPageTypeW', function ($rootScope, $routeParams) { var templateName = 'productPageTypeW'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', childcomponent: '@childcomponent', imgpath: '@imgpath' }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.referral = $routeParams.referral_id || 0; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var d = {'txt_referral_type_id': 11,'txt_sortby':'referral_sort_index_asc_name_asc'}; var dd = {'txt_referral_type_id': 12}; GAEAPI.get('referral/map', d, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; console.log("ReferralDisplayArraypus :", $scope.ReferralDisplayArray); } }); GAEAPI.get('referral/map', dd, $scope).then(function (e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } $scope.FetchDisplayCategoryForid = function () { $scope.ReferralDisplayArray = []; $scope.ReferralBrandArray = []; var datasent = { 'txt_referral_id': $scope.referral, }; GAEAPI.get('referral/id', datasent, $scope).then(function (e) { if (e.ok === 1) { $scope.Refbyidparent = e.data; } }); }; $scope.FetchDisplayCategoryForid(); /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function () { return $routeParams || false; }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function (newValue, oldValue) { if (!newValue) return; }); /* * params listener * @params (default) * @return function */ $scope.$watch('referral', function (newValue, oldValue) { if (newValue != 0) { $scope.getProduct(newValue); } else if(newValue == 0 || !newValue) { $scope.getAllProduct(); } }); $scope.fetchType = 0; $scope.fetchTimes = 1; $scope.fetchLimit = 9; /* * fetch product by referral * @params rererral_id (integer) * @return {Array} */ $scope.productState = {load: true, done: false}; $scope.productArray = []; $scope.getProduct = function (ref_id) { $scope.fetchType = 0; if (typeof ref_id === 'undefined' || ref_id === 0) { $scope.productArray = []; $scope.productState.load = true; $scope.productState.done = true; return; } /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; option.referral_id_array=[ref_id]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': ($scope.fetchTimes > 1) ? $scope.fetchLimit : $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: ref", dataSend, option, $scope.fetchTimes); }); }; /* * fetch product all * @params none * @return {Array} */ $scope.getAllProduct = function () { $scope.fetchType = 1; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array=[18]; var dataSend = { 'cur_page': $scope.fetchTimes, 'per_page': ($scope.fetchTimes > 1) ? $scope.fetchLimit : $scope.fetchLimit, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function (e) { if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; } else { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); } $scope.fetchTimes++; $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get: all", dataSend, option, $scope.fetchTimes); }); }; $scope.loadMore = function(){ if($scope.fetchType == 1){ $scope.getAllProduct(); } else { $scope.getProduct($scope.referral); } }; /* CHeck If Seo SIte */ $scope.checkSeoLink = function(productId){ return (GURL.isHtml5Mode()) ? 'product-detail/'+productId : '#/product-detail/'+productId; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('productPageTypeWc', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeWc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { menu: '@menu', referralmap: '@referralmap', referralmapbrand: '@referralmapbrand', filter: '@filter', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = false; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.returnJson = function(data, callback) { var json = JSON.parse(data); callback(json); }; $scope.referral_map = []; $scope.referralMapToJson = function() { $scope.returnJson($scope.referralmap, function(json) { if (json.length != 0) { $scope.referral_map = json; } else { setTimeout(function() { $scope.referralMapToJson(); }, 1000); } }); }; $scope.referralMapToJson(); $scope.referral_map_brand = []; $scope.referralMapBrandToJson = function() { $scope.returnJson($scope.referralmapbrand, function(json) { if (json.length != 0) { $scope.referral_map_brand = json; } else { setTimeout(function() { $scope.referralMapBrandToJson(); }, 1000); } }); }; $scope.referralMapBrandToJson(); $scope.menufilter = []; $scope.menufilterToJson = function() { $scope.returnJson($scope.filter, function(json) { if (json.length != 0) { $scope.filter_ = json; } else { setTimeout(function() { $scope.menufilterToJson(); }, 1000); } }); }; $scope.menufilterToJson(); $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeObb : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.cover_top = "PRODUCTS"; $scope.sub_products = "0"; $scope.state = ""; $scope.dataRelation = []; $scope.dataRelationState = $scope.getData().stateData(false, false); $scope.dataArrayMain = []; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "PRODUCTS"; $scope.cover_background_image_top = ""; $scope.state = "main_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "PRODUCTS"; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { console.log('referral/id : output : ', output); $scope.cover_top = output.data.referral_name; if (output.data.referral_image.length != 0) { $scope.cover_background_image_top = output.data.referral_image[0].image_url; } }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.cover_top = "PRODUCTS"; $scope.cover_background_image_top = ""; $scope.state = "sub_category"; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArrayMain = output.data; }); }); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/id', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.cover_top = output.data.referral_name; }); }); $scope.dataRelationState = $scope.getData().stateData(true, false); var dataSend = { 'txt_referral_id': params.referral_id }; $scope.getData().dataSend('referral/relation', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataRelation = output.data; $scope.dataRelationState = $scope.getData().stateData(false, true); }); }); var dataSend = { 'txt_referral_type_id': 11, 'txt_parent_id': params.referral_id, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data; $scope.sub_products = params.referral_id; if (output.data == 0) { $scope.state = "sub_category_products"; } $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.cover_top = params.sendtag; $scope.state = "sendtag_products"; $scope.cover_background_image_top = ""; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { if (params.badge_id == "72") { $scope.cover_top = "NEW PRODUCT"; } else if (params.badge_id == "74") { $scope.cover_top = "BEST SELLER"; } else if (params.badge_id == "75") { $scope.cover_top = "RECOMMEND"; } $scope.cover_background_image_top = ""; $scope.state = "badge_products"; $scope.sub_products = params.badge_id; $scope.dataRelationState = $scope.getData().stateData(false, true); $scope.dataArrayState = $scope.getData().stateData(false, true); } else { $scope.dataArrayState = $scope.getData().stateData(false, true); } }); $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_lastest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData, price: $scope.price }; console.log("pageAndData data : ", data); var page = "category-lists"; if (typeof data.root_id != 'undefined' && data.root_id !== "") { page += '?root_id=' + data.root_id; if (typeof data.referral_id != 'undefined' && data.referral_id !== "") { page += '&referral_id=' + data.referral_id; } else { delete data.referral_id; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } else if (typeof data.sendtag != 'undefined' && data.sendtag !== "") { page += '?sendtag=' + data.sendtag; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } if (typeof data.referral_id_map != 'undefined' && data.referral_id_map !== "") { page += '&referral_id_map=' + data.referral_id_map; } else { delete data.referral_id_map; } } else if (typeof data.badge_id != 'undefined' && data.badge_id !== "") { page += '?badge_id=' + data.badge_id; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } } $location.url(page).replace(); }; $scope.price = { min: 0, max: 9999999 }; $scope.setPrice = function() { console.log("setPrice : price : ", $scope.price); }; }; return promise; });_ui_share_app.directive('productPageTypeX', function($rootScope, $routeParams, $location) { var templateName = 'productPageTypeX'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = {}; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope._mapArray = []; $scope._getDataArray = function() { var dataSend = { 'txt_referral_type_id': 11, }; GAEAPI.get('referral/map', dataSend).then(function(res) { if (res.ok === 1) { $scope._mapArray = res.data; } }); }; $scope._getDataArray(); $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeY', function($rootScope, $routeParams) { var templateName = 'productPageTypeY'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', heading_:'@heading', childcomponent: '@childcomponent', imgpath: '@imgpath', imgcart: '@imgcart', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; /* * fetch only referral category type (tree-list); * @params none * @return {Array} */ $scope._params = $routeParams.referral_id; $scope.ReferralDisplayArray = []; $scope.ReferralDisplayArrayState = { load: true, done: false }; $scope.ReferralBrandArray = []; $scope.FetchDisplayCategory = function() { $scope.ReferralDisplayArrayState.load = true; $scope.ReferralDisplayArrayState.done = false; $scope.ReferralDisplayArray = []; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplayArray = e.data; } $scope.ReferralDisplayArrayState.load = false; $scope.ReferralDisplayArrayState.done = true; console.log("referral display", e.data); }); $scope.ReferralBrandArray = []; var dd = { 'txt_referral_type_id': 12 }; GAEAPI.get('referral/map', dd, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralBrandArray = e.data; } }); }; $scope.ReferralDisplaylistsArray = []; $scope.ReferralDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayCategorylists = function(dataID) { $scope.ReferralDisplaylistsArrayState.load = true; $scope.ReferralDisplaylistsArrayState.done = false; $scope.ReferralDisplaylistsArray = []; var d = { 'txt_referral_type_id': 11, 'txt_parent_id': dataID, 'txt_sortby': 'referral_sort_index_asc_name_asc' }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok === 1) { $scope.ReferralDisplaylistsArray = e.data; } $scope.ReferralDisplaylistsArrayState.load = false; $scope.ReferralDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.ReferralDisplaylistsArray); }); }; $scope.NameDisplaylistsArray = []; $scope.NameDisplaylistsArrayState = { load: true, done: false }; $scope.FetchDisplayNameDisplaylistsArray = function(dataID) { $scope.NameDisplaylistsArrayState.load = true; $scope.NameDisplaylistsArrayState.done = false; $scope.NameDisplaylistsArray = []; var d = { 'txt_referral_id': dataID }; GAEAPI.get('referral/id', d, $scope).then(function(e) { if (e.ok === 1) { $scope.NameDisplaylistsArray = e.data; } $scope.NameDisplaylistsArrayState.load = false; $scope.NameDisplaylistsArrayState.done = true; console.log("ReferralDisplaylistsArray :", $routeParams, $scope.NameDisplaylistsArray); }); }; if ($routeParams.referral_id != 'undefined') { $scope.FetchDisplayCategorylists($routeParams.referral_id); $scope.FetchDisplayNameDisplaylistsArray($routeParams.referral_id); } if (!$scope.ReferralDisplayArray.length) { $scope.FetchDisplayCategory(); } /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; $scope._data_referral_relate_ = []; $scope._get_referral_relate_ = function (array) { var dataSend = { 'txt_referral_id': array, }; GAEAPI.get('referral/relation', dataSend).then(function (e) { if (e.ok === 1) { $scope._data_referral_relate_ = e.data; } }); }; /* * params listener * @params (default) * @return function */ $scope.$watch('_params', function(newValue, oldValue) { if(newValue){ $scope._get_referral_relate_(newValue); } if (!newValue) return; }); /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; }; return promise; });_ui_share_app.directive('productPageTypeZ', function($rootScope, $routeParams) { var templateName = 'productPageTypeZ'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { stylebutton: '@stylebutton', component: '@component', viewdata: '@viewdata', name: '@name', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeZ : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; if (params.brand != undefined) { var dataSend = {}; dataSend.cur_page = $scope.dataArrayPageState.cur_page; dataSend.per_page = $scope.dataArrayPageState.per_page; dataSend.txt_sortby = $scope.sort; if (params.referral_id != undefined) { dataSend.txt_category_id = parseInt(params.referral_id); if (params.brand != undefined) { dataSend.txt_brand_id = parseInt(params.brand); } else { dataSend.txt_brand_id = 0; } } if (params.badge != undefined) { dataSend.txt_badge_id_array = JSON.stringify([18,parseInt(params.badge)]); } else { dataSend.txt_badge_id_array = JSON.stringify([18]); } $scope.getData().dataSend('product/lists_category_brand', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; if (params.brand != undefined) { var dataSend = {}; dataSend.cur_page = $scope.dataArrayPageState.cur_page; dataSend.per_page = $scope.dataArrayPageState.per_page; dataSend.txt_sortby = $scope.sort; if (params.referral_id != undefined) { dataSend.txt_category_id = parseInt(params.referral_id); if (params.brand != undefined) { dataSend.txt_brand_id = parseInt(params.brand); } else { dataSend.txt_brand_id = 0; } } if (params.badge != undefined) { dataSend.txt_badge_id_array = JSON.stringify([18,parseInt(params.badge)]); } else { dataSend.txt_badge_id_array = JSON.stringify([18]); } $scope.getData().dataSend('product/lists_category_brand', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypeZa', function($rootScope, $routeParams) { var templateName = 'productPageTypeZa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { stylebutton: '@stylebutton', component: '@component', viewdata: '@viewdata', name: '@name', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { /* console.log('productPageTypeZ : ', name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; var txt_filter_json = {}; var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; var txt_filter_json = {}; var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypeZaa', function($rootScope, $routeParams) { var templateName = 'productPageTypeZaa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { stylebutton: '@stylebutton', component: '@component', viewdata: '@viewdata', name: '@name', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeZaa : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypeZab', function($rootScope, $routeParams) { var templateName = 'productPageTypeZab'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { stylebutton: '@stylebutton', component: '@component', viewdata: '@viewdata', name: '@name', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { /* console.log('productPageTypeZab : ', name, data); */ }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 6, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypeZc', function($rootScope, $routeParams) { var templateName = 'productPageTypeZc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', component: '@component', referral: '@referral', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.$watch('tagname', function(newValue, oldValue) { console.log("tagname", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(0, newValue); } }); $scope.$watch('referral', function(newValue, oldValue) { console.log("newValue,oldValue", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue, 0); } }); $scope.productState = { load: true, done: false }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getProduct($routeParams.referral_id,0); }, 300); }; $scope.productArray = []; $scope.fetchTime = 1; $scope.all_page = true; $scope.getProduct = function(ref_id, tag) { /* Set loading state */ $scope.productState = { load: true, done: false }; /* Begin Settingup Date */ console.log("tagname", ref_id, tag); var option = {}; option.badge_id_array = [18]; if (ref_id != 0) { option.referral_id_array = [ref_id]; } if (tag != 0) { option.tags = tag; } if ($scope._viewRouteParams().badge != undefined) { option.badge_id_array = [18,$scope._viewRouteParams().badge]; } if ($scope.sort != '' || typeof $scope.sort === 'undefined') { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 24, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; } else { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 24, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(option) }; } console.log("tagname dataSend : ", dataSend); /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { if ($scope.productArray.length) { // $scope.productArray = e.data.dataList; var curData = $scope.productArray; $scope.productArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } }else { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } console.log("Share Component Get", dataSend, option, e); $scope.productState = { load: false, done: true }; }); }; }; return promise; });_ui_share_app.directive('productPageTypeZd', function($rootScope, $routeParams) { var templateName = 'productPageTypeZd'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', component: '@component', referral: '@referral', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.$watch('tagname', function(newValue, oldValue) { console.log("tagname", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(0, newValue); } }); $scope.$watch('referral', function(newValue, oldValue) { console.log("newValue,oldValue", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue, 0); } }); $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id, tag) { /* Set loading state */ $scope.productState = { load: true, done: false }; /* Begin Settingup Date */ console.log("tagname", ref_id, tag); var option = {}; option.badge_id_array = [18]; if (ref_id != 0) { option.referral_id_array = [ref_id]; } if (tag != 0) { option.tags = tag; } if ($scope._viewRouteParams().badge != undefined) { option.badge_id_array = [18, $scope._viewRouteParams().badge]; } if ($scope.sort != '' || typeof $scope.sort === 'undefined') { var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; } else { var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(option) }; } console.log("tagname dataSend : ", dataSend); /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } console.log("Share Component Get", dataSend, option, e); $scope.productState = { load: false, done: true }; }); }; }; return promise; });_ui_share_app.directive('productPageTypeZf', function($rootScope, $routeParams) { var templateName = 'productPageTypeZf'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', component: '@component', referral: '@referral', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.$watch('tagname', function(newValue, oldValue) { console.log("tagname", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(0, newValue); } }); $scope.$watch('referral', function(newValue, oldValue) { console.log("newValue,oldValue", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue, 0); } }); $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.getProduct = function(ref_id, tag) { /* Set loading state */ $scope.productState = { load: true, done: false }; /* Begin Settingup Date */ console.log("tagname", ref_id, tag); var option = {}; option.badge_id_array = [18]; if (ref_id != 0) { option.referral_id_array = [ref_id]; } if (tag != 0) { option.tags = tag; } if ($scope._viewRouteParams().badge != undefined) { option.badge_id_array = [18,$scope._viewRouteParams().badge]; } if ($scope.sort != '' || typeof $scope.sort === 'undefined') { var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; } else { var dataSend = { 'cur_page': 1, 'per_page': 100, 'txt_filter_json': JSON.stringify(option) }; } console.log("tagname dataSend : ", dataSend); /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { $scope.productArray = e.data.dataList; } console.log("Share Component Get", dataSend, option, e); $scope.productState = { load: false, done: true }; }); }; }; return promise; });_ui_share_app.directive('productPageTypeZg', function($rootScope, $routeParams) { var templateName = 'productPageTypeZg'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', component: '@component', referral: '@referral', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.$watch('tagname', function(newValue, oldValue) { console.log("tagname", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(0, newValue); } }); $scope.$watch('referral', function(newValue, oldValue) { console.log("newValue,oldValue", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue, 0); } }); $scope.productState = { load: true, done: false }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getProduct($routeParams.referral_id,0); }, 300); }; $scope.productArray = []; $scope.fetchTime = 1; $scope.all_page = true; $scope.getProduct = function(ref_id, tag) { /* Set loading state */ $scope.productState = { load: true, done: false }; /* Begin Settingup Date */ console.log("tagname", ref_id, tag); var option = {}; option.badge_id_array = [18]; if (ref_id != 0) { option.referral_id_array = [ref_id]; } if (tag != 0) { option.tags = tag; } if ($scope._viewRouteParams().badge != undefined) { option.badge_id_array = [18,$scope._viewRouteParams().badge]; } if ($scope.sort != '' || typeof $scope.sort === 'undefined') { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 24, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; } else { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 24, 'txt_sortby': 'product_category_sort_index_asc', 'txt_filter_json': JSON.stringify(option) }; } console.log("tagname dataSend : ", dataSend); /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { if ($scope.productArray.length) { // $scope.productArray = e.data.dataList; var curData = $scope.productArray; $scope.productArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } }else { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } console.log("Share Component Get", dataSend, option, e); $scope.productState = { load: false, done: true }; }); }; }; return promise; });_ui_share_app.directive('productPageTypeZga', function($rootScope, $routeParams) { var templateName = 'productPageTypeZga'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', component: '@component', referral: '@referral', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sort: '@sort', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.$watch('tagname', function(newValue, oldValue) { console.log("tagname", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(0, newValue); } }); $scope.$watch('referral', function(newValue, oldValue) { console.log("newValue,oldValue", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(newValue, 0); } }); $scope.productState = { load: true, done: false }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getProduct($routeParams.referral_id, 0); }, 300); }; $scope.productArray = []; $scope.fetchTime = 1; $scope.all_page = true; $scope.getProduct = function(ref_id, tag) { /* Set loading state */ $scope.productState = { load: true, done: false }; /* Begin Settingup Date */ console.log("tagname", ref_id, tag); var option = {}; option.badge_id_array = [18]; if (ref_id != 0) { option.referral_id_array = [ref_id]; } if (tag != 0) { option.tags = tag; } if ($scope._viewRouteParams().badge != undefined) { option.badge_id_array = [18, $scope._viewRouteParams().badge]; } if ($scope.sort != '' || typeof $scope.sort === 'undefined') { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 24, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; } else { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 24, 'txt_sortby': 'product_category_sort_index_asc', 'txt_filter_json': JSON.stringify(option) }; } console.log("tagname dataSend : ", dataSend); /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { if ($scope.productArray.length) { // $scope.productArray = e.data.dataList; var curData = $scope.productArray; $scope.productArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } else { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } console.log("Share Component Get", dataSend, option, e); $scope.productState = { load: false, done: true }; }); }; }; return promise; });_ui_share_app.directive('productPageTypeZh', function($rootScope, $routeParams) { var templateName = 'productPageTypeZh'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', referralid: '@referral', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sort: '@sort', limitdata: '@limitdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._sortproduct = (typeof $scope.sort !== 'undefined' && typeof $scope.sort !== '') ? $scope.sort : 'product_lastest_create'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 24; $scope._additional = 1; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "referral_id_array": [id], } var dataSend = { 'cur_page': $scope._additional, 'per_page': $scope._limitdata, 'txt_sortby': $scope._sortproduct, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_product', dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(res) { if (res.ok === 1) { if ($scope._dataArray.length) { $scope.all_page = $scope.StateMore(res.data.total_rows, $scope._dataArray.length, $scope._limitdata); var curData = $scope._dataArray; $scope._dataArray = curData.concat(res.data.dataList); } else { $scope.all_page = $scope.StateMore(res.data.total_rows, $scope._dataArray.length, $scope._limitdata); $scope._dataArray = res.data.dataList; } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateMore = function(number_1, number_2, number_3) { var State = true; console.log('dataSend_product', number_1, (number_2 + 1), number_3); if (number_2 == 0) { if (number_1 <= number_3) { State = false; } else { State = true; } } else { if (number_1 <= (number_2 + 1)) { State = false; } else { State = true; } } return State; }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getProductArray($scope.referralid); $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope._additional++; $scope.loadMore_is_load = true; $timeout(function() { $scope._getProductArray($scope.referralid); }, 300); }; }; return promise; });_ui_share_app.directive('productPageTypeZm', function($rootScope, $routeParams) { var templateName = 'productPageTypeZm'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { component: '@component', referralid: '@referral', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sort: '@sort', limitdata: '@limitdata', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._sortproduct = (typeof $scope.sort !== 'undefined' && typeof $scope.sort !== '') ? $scope.sort : 'product_lastest_create'; $scope._limitdata = (typeof $scope.limitdata !== 'undefined' && typeof $scope.limitdata !== '') ? $scope.limitdata : 24; $scope._additional = 1; $scope._dataArray = []; $scope._dataArrayState = { load: true, done: false }; $scope._getProductArray = function(id) { $scope._dataArrayState = $scope.StateData(true, false); var filter_json = { "referral_id_array": [id], } var dataSend = { 'cur_page': $scope._additional, 'per_page': $scope._limitdata, 'txt_sortby': $scope._sortproduct, 'txt_filter_json': JSON.stringify(filter_json) }; console.log('dataSend_product', dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(res) { if (res.ok === 1) { if ($scope._dataArray.length) { $scope.all_page = $scope.StateMore(res.data.total_rows, $scope._dataArray.length, $scope._limitdata); var curData = $scope._dataArray; $scope._dataArray = curData.concat(res.data.dataList); } else { $scope.all_page = $scope.StateMore(res.data.total_rows, $scope._dataArray.length, $scope._limitdata); $scope._dataArray = res.data.dataList; } } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateMore = function(number_1, number_2, number_3) { var State = true; console.log('dataSend_product', number_1, (number_2 + 1), number_3); if (number_2 == 0) { if (number_1 <= number_3) { State = false; } else { State = true; } } else { if (number_1 <= (number_2 + 1)) { State = false; } else { State = true; } } return State; }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; }; $scope._getLoad = function(id) { var data_length = $('.product_cat_id[referral-id="' + id + '"]').length; var stateLoad = true; if (data_length == 0) { stateLoad = true; } else { stateLoad = false; } return stateLoad; }; $scope._getProductArray($scope.referralid); $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope._additional++; $scope.loadMore_is_load = true; $timeout(function() { $scope._getProductArray($scope.referralid); }, 300); }; }; return promise; });_ui_share_app.directive('productPageTypeZoca', function($rootScope, $routeParams) { var templateName = 'productPageTypeZoca'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', sort: '@sort', cardgrid: '@cardgrid', cardlist: '@cardlist', viewdata: '@viewdata', styletextgrid: '@styletextgrid', stylebuttongrid: '@stylebuttongrid', imgcartgrid: '@imgcartgrid', styletextlist: '@styletextlist', stylebuttonlist: '@stylebuttonlist', imgcartlist: '@imgcartlist', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productPageTypeZoca : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.state = ""; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { if (params.brand == undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } else { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id), parseInt(params.brand)]; } } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); } else { $scope.state = ""; } }); $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "main_category"; } else if (params.root_id == '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id != '0' && params.referral_id != undefined && params.sendtag == undefined && params.badge_id == undefined) { $scope.state = "sub_category"; var txt_filter_json = {}; /* if (params.referral_id != undefined) { txt_filter_json.referral_id_array = [parseInt(params.referral_id)]; } */ if (params.referral_id != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag != undefined && params.badge_id == undefined) { $scope.state = "sendtag_products"; var txt_filter_json = {}; if (params.sendtag != undefined) { txt_filter_json.tags = params.sendtag; } if (params.referral_id_map != undefined) { txt_filter_json.referral_id_array_in = [parseInt(params.referral_id_map)]; } if (params.badge != undefined) { txt_filter_json.badge_id_array = [parseInt(params.badge)]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else if (params.root_id == undefined && params.referral_id == undefined && params.sendtag == undefined && params.badge_id != undefined) { $scope.state = "badge_products"; var txt_filter_json = {}; if (params.badge_id != undefined) { txt_filter_json.badge_id_array = [params.badge_id]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); } else { $scope.state = ""; } }); } }; }; return promise; });_ui_share_app.directive('productPageTypeZocb', function($rootScope, $routeParams) { var templateName = 'productPageTypeZocb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', component: '@component', referral: '@referral', tagname: '@tagname', stylebutton: '@stylebutton', viewdata: '@viewdata', sort: '@sort', styletext: '@styletext', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.showDebug = function() { return (typeof $routeParams.debugproduct !== 'undefined') ? true : false; }; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.$watch('tagname', function(newValue, oldValue) { console.log("tagname", newValue, oldValue); if (!newValue) return; if (newValue != 0) { $scope.getProduct(0, newValue); } }); $scope.$watch('referral', function(newValue, oldValue) { console.log("newValue,oldValue", newValue, oldValue); if (!newValue){ $scope.getProduct(0,0); } if (newValue != 0 && newValue != undefined) { // alert(newValue); $scope.getProduct(newValue, 0); } }); $scope.productState = { load: true, done: false }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getProduct($routeParams.referral_id,0); }, 300); }; $scope.productArray = []; $scope.fetchTime = 1; $scope.all_page = true; $scope.getProduct = function(ref_id, tag) { /* Set loading state */ $scope.productState = { load: true, done: false }; /* Begin Settingup Date */ console.log("tagname", ref_id, tag); var option = {}; option.badge_id_array = [18]; if (ref_id != 0) { option.referral_id_array = [ref_id]; } if (tag != 0) { option.tags = tag; } if ($scope._viewRouteParams().badge != undefined) { option.badge_id_array = [18,$scope._viewRouteParams().badge]; } if ($scope.sort != '' || typeof $scope.sort === 'undefined') { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 24, 'txt_sortby': $scope.sort, 'txt_filter_json': JSON.stringify(option) }; } else { var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 24, 'txt_sortby': 'product_lastest_create', 'txt_filter_json': JSON.stringify(option) }; } console.log("tagname dataSend : ", dataSend); /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { if ($scope.productArray.length) { // $scope.productArray = e.data.dataList; var curData = $scope.productArray; $scope.productArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } }else { $scope.productArray = e.data.dataList; if (e.data.total_rows <= $scope.productArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } console.log("Share Component Get", dataSend, option, e); $scope.productState = { load: false, done: true }; }); }; }; return promise; });// _ui_share_app.filter('productPriceFilter', function() { // return function(items, inputConfig) { // var filtered = []; // var min = parseInt(inputConfig.min); // var max = parseInt(inputConfig.max); // angular.forEach(items, function(item) { // if (parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { // filtered.push(item); // } // }); // return filtered; // }; // }); _ui_share_app.directive('productSearchPage', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productSearchPage'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_price_desc'; $scope.changeFilterSortData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '10'; $scope.changefilterPerPageData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { }; $scope.doFilterBy = function(isChecked, badgeId) { }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } if (typeof $routeParams.search !== 'undefined' && $routeParams.search != '') { /* check if array */ json_filter.search = $routeParams.search; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } /* check sort */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 10, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* search-result name of this search-result */ search: $scope.viewRouteParams().search, /* category name of this category */ badge: badgeIdArray, /* view name of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'search-result'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.search !== 'undefined' && path.search !== "") { strHref += '?search=' + path.search; } else { delete path.search; /*strHref += '?root_id=0';*/ } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); if($(window).height() > 595){ $('.erere').css('min-height',(($(window).height() - 145)+'px')); // alert($(window).height() - 145); } angular.element($window).bind('scroll', function() { var curPos = ($(document).scrollTop()); var properHeight = ($('.erere').height()); console.debug("Cur pos", curPos, properHeight); if($(window).width() > 991){ if ((curPos + ($(window).height() - 145)) > properHeight ) { if ((properHeight - curPos) <= ($(window).height() - 145)) { if(properHeight - ($(window).height() - 145) < 0){ /* document.getElementsByClassName('testrewq')[0].style.top = "0px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = "0px"; */ $('.testrewq').css('top','0px'); $('.testrewq').css('margin-bottom','0px'); }else{ $('.testrewq').css('top',(properHeight - ($(window).height() - 145)) + 'px'); $('.testrewq').css('margin-bottom',(properHeight - ($(window).height() - 145)) + 'px'); /* document.getElementsByClassName('testrewq')[0].style.top = (properHeight - ($(window).height() - 145)) + "px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = (properHeight - ($(window).height() - 145)) + "px"; */ } } else { $('.testrewq').css('top','auto'); /* document.getElementsByClassName('testrewq')[0].style.top = "auto"; */ } angular.element('.testrewq').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { $('.testrewq').css('top','auto'); /* document.getElementsByClassName('testrewq')[0].style.top = "auto"; */ angular.element('.testrewq').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }else{ angular.element('.testrewq').removeClass('unactive'); } }); }; return promise; });_ui_share_app.directive('productSearchPageB', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productSearchPageB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { // $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { // $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { }; $scope.doFilterBy = function(isChecked, badgeId) { }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } if (typeof $routeParams.search !== 'undefined' && $routeParams.search != '') { /* check if array */ json_filter.search = $routeParams.search; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { console.log("product/lists : dataSend : ",dataSend); GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* search-result name of this search-result */ search: $scope.viewRouteParams().search, /* category name of this category */ badge: badgeIdArray, /* view name of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'search-result'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.search !== 'undefined' && path.search !== "") { strHref += '?search=' + path.search; } else { delete path.search; /*strHref += '?root_id=0';*/ } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; }; return promise; });_ui_share_app.directive('productSearchPageC', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewType = 'grid'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.productListSort = $scope._viewRouteParams().sort || "product_lifetime_start_asc"; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('search-result') !== -1) ? '/search-result' : '/search-result'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { otherParams += "&referral_type=" + 'category'; paramsObj.referral_type = 'category'; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $location.path(pathStr).search(paramsObj); }, 300); }; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = {}; txt_filter_json.badge_id_array = [18]; txt_filter_json.search = $scope._viewRouteParams().search; if (typeof $scope._viewRouteParams().referral_array !== 'undefined' && $scope._viewRouteParams().referral_array != '') { var refOArray = $scope._viewRouteParams().split(','); if ($scope._viewRouteParams().indexOf(',') != -1 && refOArray.length > 0) { txt_filter_json.referral_id_array_in = refOArray; } else { txt_filter_json.referral_id_array_in = [refOArray]; } } var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': $scope.productListSort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; console.log("getProduct : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); }; return promise; });_ui_share_app.directive('productSearchPageCa', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageCa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewType = 'grid'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.productListSort = $scope._viewRouteParams().sort || "product_lastest_create"; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('search-result') !== -1) ? '/search-result' : '/search-result'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { otherParams += "&referral_type=" + 'category'; paramsObj.referral_type = 'category'; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $location.path(pathStr).search(paramsObj); }, 300); }; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = {}; txt_filter_json.badge_id_array = [18]; txt_filter_json.search = $scope._viewRouteParams().search; if (typeof $scope._viewRouteParams().referral_array !== 'undefined' && $scope._viewRouteParams().referral_array != '') { var refOArray = $scope._viewRouteParams().split(','); if ($scope._viewRouteParams().indexOf(',') != -1 && refOArray.length > 0) { txt_filter_json.referral_id_array_in = refOArray; } else { txt_filter_json.referral_id_array_in = [refOArray]; } } var dataSend = { 'cur_page': 1, 'per_page': 20, 'txt_sortby': $scope.productListSort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(output) { if (output.ok == 1) { $scope._dataArray = output.data.dataList; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); }; return promise; });_ui_share_app.directive('productSearchPageD', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageD'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewType = 'grid'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.productListSort = $scope._viewRouteParams().sort || "referral_sort_index_asc_name_asc"; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('search-result') !== -1) ? '/search-result' : '/search-result'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { otherParams += "&referral_type=" + 'category'; paramsObj.referral_type = 'category'; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope._dataArray = []; $location.path(pathStr).search(paramsObj); }, 300); }; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.all_page = true; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = {}; txt_filter_json.badge_id_array = [18]; txt_filter_json.search = $scope._viewRouteParams().search; if (typeof $scope._viewRouteParams().referral_array !== 'undefined' && $scope._viewRouteParams().referral_array != '') { var refOArray = $scope._viewRouteParams().split(','); if ($scope._viewRouteParams().indexOf(',') != -1 && refOArray.length > 0) { txt_filter_json.referral_id_array_in = refOArray; } else { txt_filter_json.referral_id_array_in = refOArray; } } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 20, 'txt_sortby': $scope.productListSort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; console.log("product/lists : dataSend : ",dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { if ($scope._dataArray.length) { var curData = $scope._dataArray; $scope._dataArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } else { $scope._dataArray = e.data.dataList; if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } // $scope.data_product_done = true; // console.log("Zoom: getDataProduct: e , new data", e); } // $scope._dataArray = e.data.dataList; } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.fetchTime = 1; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope._getDataArray(); }, 300); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); }; return promise; });_ui_share_app.directive('productSearchPageDa', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageDa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productSearchPageDa : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_oldest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().brand || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { search: inRouteParams.search, referral_array: inRouteParams.referral_array, sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "search-result"; if (typeof data.search != 'undefined' && data.search !== "") { page += '?search=' + data.search; if (typeof data.referral_array != 'undefined' && data.referral_array !== "") { page += '&referral_array=' + data.referral_array; } else { delete data.referral_array; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [params.referral_array]; } } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json), 'from': moment().unix() }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); }); } }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [params.referral_array]; } } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); /* $scope.viewType = 'grid'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.productListSort = $scope._viewRouteParams().sort || "referral_sort_index_asc_name_asc"; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('search-result') !== -1) ? '/search-result' : '/search-result'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { otherParams += "&referral_type=" + 'category'; paramsObj.referral_type = 'category'; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope._dataArray = []; $location.path(pathStr).search(paramsObj); }, 300); }; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.all_page = true; $scope.total_product = 0; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = {}; txt_filter_json.badge_id_array = [18]; txt_filter_json.search = $scope._viewRouteParams().search; if (typeof $scope._viewRouteParams().referral_array !== 'undefined' && $scope._viewRouteParams().referral_array != '') { var refOArray = $scope._viewRouteParams().split(','); if ($scope._viewRouteParams().indexOf(',') != -1 && refOArray.length > 0) { txt_filter_json.referral_id_array_in = refOArray; } else { txt_filter_json.referral_id_array_in = [refOArray]; } } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 20, 'txt_sortby': $scope.productListSort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { $scope.total_product = e.data.total_rows; if ($scope._dataArray.length) { var curData = $scope._dataArray; $scope._dataArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } else { $scope._dataArray = e.data.dataList; if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.fetchTime = 1; $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope._getDataArray(); }, 300); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray();*/ }; return promise; });// _ui_share_app.filter('productPriceFilter_myhappy', function() { // return function( items, inputConfig ) { // var filtered = []; // var min = parseInt(inputConfig.min); // var max = parseInt(inputConfig.max); // var brand = inputConfig.brand; // var text = ""; // angular.forEach(items, function(item) { // if(parseInt(item.product_price) >= min && parseInt(item.product_price) <= max) { // if(brand.length == 0){ // filtered.push(item); // }else{ // if(item.product_referral_display.brand != undefined){ // for(var i=0;i 1 && !e.data.dataList.length) { $scope.loadNoMore1 = true; } } $scope.tag_arrayStatedone = true; $scope.tag_arrayStateload = false; }); }; /* * get referral data * @params {referralId} * @params {parentId} a.k.a root_id * @return array */ console.log("referal_testparent : 1", $scope.categoryThisParent); $scope.getThisReferral = function(referralId, parentId) { GAEAPI.get('referral/id', { 'txt_referral_id': referralId }).then(function(e) { if (e.ok == 1) { $scope.categoryThis = e.data; if (e.data.referral_parent_id != 0) { GAEAPI.get('referral/id', { 'txt_referral_id': e.data.referral_parent_id }).then(function(res) { if (res.ok == 1) { $scope.categoryThisParent = res.data; console.log("referal_testparent : ", $scope.categoryThisParent); } }); }; } }); }; /* * Watch get params to query referal data */ $scope.$watch('_get_referral_id', function(newValue, oldValue) { if (!newValue) return; $scope.getThisReferral(newValue, $scope._viewRouteParams().root_id); }); $scope.$watch('tag_name', function(newValue, oldValue) { if (!newValue) {} else { $scope.getTagarray(newValue, $scope.loadTime1); } }); /* * Fetch Category * @params none * @return array */ $scope.categoryArray = []; $scope.categoryLoad = false; $scope.categoryDone = false; $scope.getReferral = function() { $scope.categoryLoad = true; $scope.categoryDone = false; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok == 1) { $scope.categoryArray = e.data; } $scope.categoryLoad = false; $scope.categoryDone = true; }); }; if (!$scope.categoryArray.length) { $scope.getReferral(); } $scope.buildCatgegoryMobile(); /* * Arrange : brand * @params {objectArray} * @return array */ $scope.brandArray = []; $scope.getBrandList = function() { var d = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 50, 'txt_sortby': 'referral_name_a-z' }; GAEAPI.get('referral/lists', d).then(function(e) { if (e.ok == 1 && e.data.dataList.length) { $scope.brandArray = e.data.dataList; } }); }; $scope.getBrandList(); $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = ""; $scope.productListSort = $scope._viewRouteParams().sort || "product_oldest_create"; $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; $scope.loadTime = 1; $scope.all_item = 0; $scope.set_loadmore = true; $scope.loadNoMore = false; $scope.getProduct = function() { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; /* Check: Search */ if (typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== "") { option.search = $scope._viewRouteParams().search; } /* Check: referral */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { option.referral_id_array_in = refOArray; } else { option.referral_id_array_in = [refOArray]; } } /* Check: badge */ if (typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != "") { /* Check Badge from URL */ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit, function(i, k) { option.badge_id_array.push(i); }); } else if ($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false) { /* Check Badge from component (multibadge) */ if ($scope.badgeid.indexOf(',') == -1) { var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i, k) { var test = i.trim(); if (option.badge_id_array.indexOf(test) == -1) { /* check exist */ option.badge_id_array.push(i.trim()); } }); } else { /* Check Badge from component (1 badge) */ var test = $scope.badgeid.trim(); if (option.badge_id_array.indexOf(test) == -1) { /* check exist */ option.badge_id_array.push($scope.badgeid.trim()); } } } /* Check Filter_data (brand,price,other) */ if (typeof $scope._viewRouteParams().filter_data !== 'undefined' && typeof $scope._viewRouteParams().filter_data != "") { var a = $scope._viewRouteParams().filter_data.split('|'); option.referral_id_array_in = []; for (var i = 0; i < a.length; i++) { var b = a[i].split('@'); if (b[0] == 'brand') { /* Referral(brand) */ if (b[1].indexOf(',') !== -1) { var c = b[1].split(','); for (var ii in c) { /*console.log("Share Component Get All: filter_data : array", c[ii]);*/ option.referral_id_array_in.push(c[ii]); } } else { option.referral_id_array_in.push(b[1]); /*console.log("Share Component Get All: filter_data : single", b[1]);*/ } } if (b[0] == 'price') { /* Price */ } } /*console.log("Share Component Get All: filter_data", a);*/ } /* Check: sort by */ var sortBy = 'product_oldest_create'; if (typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != "") { var r = $scope._viewRouteParams().sort; switch (r) { case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var curPage = (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1; if ($scope.loadTime > 1) { curPage = $scope.loadTime; } var dataSend = { 'cur_page': curPage, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 12, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ console.log("getProduct : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { /*if(e.data.dataList.length > 0){ $scope.productArray = e.data.dataList; $scope.buildPaginationParameter(e.data); } */ if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; $scope.all_item = e.data.total_rows; console.log("sdjksiodjsds : 0", $scope.all_item, $scope.productArray); if ($scope.all_item <= $scope.productArray.length) { $scope.set_loadmore = false; } } else { if (e.data.dataList.length) { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); $scope.all_item = e.data.total_rows; console.log("sdjksiodjsds : 1", $scope.all_item, $scope.productArray); if ($scope.all_item <= $scope.productArray.length) { $scope.set_loadmore = false; } } else if ($scope.loadTime > 1 && !e.data.dataList.length) { $scope.loadNoMore = true; } } /*console.log("productArray", $scope.productArray);*/ if ($("#feature-product").hasClass('hide')) { $('#feature-product').removeClass('hide'); } } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get All", dataSend, option, e); }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function(data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function(total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener (sortby) * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('search-result') !== -1) ? '/search-result' : '/search-result'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; $scope.productListOnSortChange1 = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('search-result') !== -1) ? '/search-result' : '/search-result'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().tagname != 'undefined' && $location.search().tagname != "") { otherParams += "&tagname=" + $location.search().tagname; paramsObj.tagname = $location.search().tagname; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; /** * select listener (item per page) * @params model (string) * @return event */ $scope.displayChange = function(e) { if (window.location.href.indexOf('search-result') !== -1) { $location.path("/search-result").search({ 'page': 1, 'per_page': e }); } else { $location.path("/search-result").search({ 'page': 1, 'per_page': e });; } }; $scope.buildFilterUrl = function(exceptionalKey) { var a = ''; angular.forEach($routeParams, function(item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i) { return parseInt(i) || false; }; $scope.printSelected = function(a) { if ($routeParams.sort == a) { return " selected"; } return " "; }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* when route change success => do something */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { console.log("pageChangedSuccess", current); if ($scope.loadTime > 1) { $scope.loadTime = 1; } $scope.getProduct(); if (!$scope.categoryArray.length && !$scope.categoryLoad.length) { $scope.getReferral(); } $scope.buildCatgegoryMobile(); }); /* FIlter FORM */ $scope.viewType = 'grid'; $scope._filter = $scope._viewRouteParams().filter_data; $scope.filterBrandModel = []; $scope.filter_brand = []; $scope.$watch('_filter', function(newValue, oldValue) { if (!newValue) return; var a = newValue.split('|'); for (var i = 0; i < a.length; i++) { var b = a[i].split('@'); if (b[0] == 'brand') { var c = b[1].split(','); for (var ii = 0; ii < c.length; ii++) { $scope.filter_brand.push(parseInt(c[ii])); } } console.log('filter_brand', $scope.filter_brand); } }); $scope.checkFilterBrand = function(val) { return ($scope.filter_brand.indexOf(parseInt(val)) !== -1) ? true : false; }; $scope.checkFilterBrandChange = function(val, isSelect) {}; /* Button to load more */ $scope.loadMore = function() { $scope.loadTime = $scope.loadTime + 1; $timeout(function() { $scope.getProduct(); }, 200); }; $scope.loadMore1 = function() { $scope.loadTime1 = $scope.loadTime1 + 1; $timeout(function() { $scope.getTagarray($scope.tag_name, $scope.loadTime1); }, 200); }; $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel, '1'); console.log("test_array :", $scope.invited); } }; }; return promise; });_ui_share_app.directive('productSearchPageEa', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productSearchPageEa'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', imgcart: '@imgcart', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; $scope._param = $routeParams; $scope.navChange = function(path) {}; /* * view current routeParams * @params (default) * @return function */ $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.rangeConfig = { min: 0, max: 100000, brand: [], }; setTimeout(function() { $('div#slider-range-2').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); }, 500); $scope.myvalue = ""; $scope.set_price = function(index, index_set) { var actor = index.split('-'); $scope.rangeConfig.min = actor[0]; $scope.rangeConfig.max = actor[1]; }; $scope.brand_id_array = []; $scope.setfilterbrand = function(brand, index) { if (brand.isChecked[brand.referral_id]) { $scope.brand_id_array.push(brand.referral_id); $scope.rangeConfig.brand = $scope.brand_id_array; console.log("test_array_brand :", $scope.brand_id_array, $scope.rangeConfig.brand); } else { var toDel = $scope.brand_id_array.indexOf(brand.referral_id); console.log("test_array_brand :", $scope.brand_id_array, toDel); $scope.brand_id_array.splice(toDel, '1'); $scope.rangeConfig.brand = $scope.brand_id_array; console.log("test_array_brand :", $scope.brand_id_array, $scope.rangeConfig.brand); } }; $scope._get_referral_id = $scope._viewRouteParams().referral_id || false; $scope.tag_name = $scope._viewRouteParams().tagname || false; $scope._get_root_id = $scope._viewRouteParams().root_id || false; $scope.categoryThis = []; $scope.categoryThisParent = []; $scope.buildCatgegoryMobile = function() { if ($('select#menuSubSelect_1 option').length <= 0) { var t = setTimeout(function() { clearTimeout(t); getReferralMap(); }, 300); } }; $scope.productListSort = $scope._viewRouteParams().sort || "product_oldest_create"; $scope.tag_array = []; $scope.tag_arrayStatedone = false; $scope.tag_arrayStateload = true; $scope.loadNoMore1 = false; $scope.loadTime1 = 1; $scope.all_item1 = 0; $scope.set_loadmore1 = true; $scope.getTagarray = function(tag, curpage) { $scope.tag_arrayStatedone = false; $scope.tag_arrayStateload = true; var option_tag = { "tags": tag, }; $scope.productTagSort = $scope._viewRouteParams().sort || ""; var d = { 'cur_page': curpage, 'per_page': 12, 'txt_sortby': $scope.productTagSort, 'txt_filter_json': JSON.stringify(option_tag), }; GAEAPI.get('product/lists', d, $scope).then(function(e) { if (e.ok === 1 && !$scope.tag_array.length) { $scope.tag_array = e.data.dataList; if ($scope.all_item1 <= $scope.tag_array.length) { $scope.set_loadmore1 = false; } } else { if (e.data.dataList.length) { var currentData = $scope.tag_array; $scope.tag_array = currentData.concat(e.data.dataList); $scope.all_item1 = e.data.total_rows; if ($scope.all_item1 <= $scope.tag_array.length) { $scope.set_loadmore1 = false; } } else if ($scope.loadTime1 > 1 && !e.data.dataList.length) { $scope.loadNoMore1 = true; } } $scope.tag_arrayStatedone = true; $scope.tag_arrayStateload = false; }); }; /* * get referral data * @params {referralId} * @params {parentId} a.k.a root_id * @return array */ console.log("referal_testparent : 1", $scope.categoryThisParent); $scope.getThisReferral = function(referralId, parentId) { GAEAPI.get('referral/id', { 'txt_referral_id': referralId }).then(function(e) { if (e.ok == 1) { $scope.categoryThis = e.data; if (e.data.referral_parent_id != 0) { GAEAPI.get('referral/id', { 'txt_referral_id': e.data.referral_parent_id }).then(function(res) { if (res.ok == 1) { $scope.categoryThisParent = res.data; console.log("referal_testparent : ", $scope.categoryThisParent); } }); }; } }); }; /* * Watch get params to query referal data */ $scope.$watch('_get_referral_id', function(newValue, oldValue) { if (!newValue) return; $scope.getThisReferral(newValue, $scope._viewRouteParams().root_id); }); $scope.$watch('tag_name', function(newValue, oldValue) { if (!newValue) {} else { $scope.getTagarray(newValue, $scope.loadTime1); } }); /* * Fetch Category * @params none * @return array */ $scope.categoryArray = []; $scope.categoryLoad = false; $scope.categoryDone = false; $scope.getReferral = function() { $scope.categoryLoad = true; $scope.categoryDone = false; var d = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', }; GAEAPI.get('referral/map', d, $scope).then(function(e) { if (e.ok == 1) { $scope.categoryArray = e.data; } $scope.categoryLoad = false; $scope.categoryDone = true; }); }; if (!$scope.categoryArray.length) { $scope.getReferral(); } $scope.buildCatgegoryMobile(); /* * Arrange : brand * @params {objectArray} * @return array */ $scope.brandArray = []; $scope.getBrandList = function() { var d = { 'txt_referral_type_id': 12, 'cur_page': 1, 'per_page': 50, 'txt_sortby': 'referral_name_a-z' }; GAEAPI.get('referral/lists', d).then(function(e) { if (e.ok == 1 && e.data.dataList.length) { $scope.brandArray = e.data.dataList; } }); }; $scope.getBrandList(); $scope.newLoginregister = function(name) { window.location.href = GURL.base_url() + name; }; /* * fetch product all * @params rererral_id (integer) * @return {Array} */ $scope.productState = { load: true, done: false }; $scope.productArray = []; $scope.cur_page = 1; $scope.per_page = ""; $scope.productListSort = $scope._viewRouteParams().sort || "product_oldest_create"; $scope.example = $scope.callback; $scope.badgeid = (typeof $scope.badgearray !== 'undefined' && $scope.badgearray != "") ? $scope.badgearray : false; $scope.loadTime = 1; $scope.all_item = 0; $scope.set_loadmore = true; $scope.loadNoMore = false; $scope.getProduct = function() { /* Reset Pagination */ $scope.pagination_data = {}; /* Set loading state */ $scope.productState.load = true; $scope.productState.done = false; /* Begin Settingup Date */ var option = {}; option.badge_id_array = [18]; /* Check: Search */ if (typeof $scope._viewRouteParams().search !== 'undefined' && typeof $scope._viewRouteParams().search !== "") { option.search = $scope._viewRouteParams().search; } /* Check: referral */ if (typeof $scope._viewRouteParams().referral_id !== 'undefined' && typeof $scope._viewRouteParams().referral_id != 0) { option.referral_id_array = [$scope._viewRouteParams().referral_id]; } /* Check: badge */ if (typeof $scope._viewRouteParams().badge !== 'undefined' && typeof $scope._viewRouteParams().badge != "") { /* Check Badge from URL */ var badgeGetSplit = $scope._viewRouteParams().badge.split(','); angular.forEach(badgeGetSplit, function(i, k) { option.badge_id_array.push(i); }); } else if ($scope.badgeid !== 'undefined' && $scope.badgeid !== '' && $scope.badgeid !== false) { /* Check Badge from component (multibadge) */ if ($scope.badgeid.indexOf(',') == -1) { var badgeSplit = $scope.badgeid.split(','); angular.forEach(badgeSplit, function(i, k) { var test = i.trim(); if (option.badge_id_array.indexOf(test) == -1) { /* check exist */ option.badge_id_array.push(i.trim()); } }); } else { /* Check Badge from component (1 badge) */ var test = $scope.badgeid.trim(); if (option.badge_id_array.indexOf(test) == -1) { /* check exist */ option.badge_id_array.push($scope.badgeid.trim()); } } } /* Check Filter_data (brand,price,other) */ if (typeof $scope._viewRouteParams().filter_data !== 'undefined' && typeof $scope._viewRouteParams().filter_data != "") { var a = $scope._viewRouteParams().filter_data.split('|'); option.referral_id_array_in = []; for (var i = 0; i < a.length; i++) { var b = a[i].split('@'); if (b[0] == 'brand') { /* Referral(brand) */ if (b[1].indexOf(',') !== -1) { var c = b[1].split(','); for (var ii in c) { /*console.log("Share Component Get All: filter_data : array", c[ii]);*/ option.referral_id_array_in.push(c[ii]); } } else { option.referral_id_array_in.push(b[1]); /*console.log("Share Component Get All: filter_data : single", b[1]);*/ } } if (b[0] == 'price') { /* Price */ } } /*console.log("Share Component Get All: filter_data", a);*/ } /* Check: sort by */ var sortBy = 'product_oldest_create'; if (typeof $scope._viewRouteParams().sort !== 'undefined' && typeof $scope._viewRouteParams().sort != "") { var r = $scope._viewRouteParams().sort; switch (r) { case 'newarrival': option.badge_id_array.push(72); break; case 'recommend': option.badge_id_array.push(74); break; case 'bestseller': option.badge_id_array.push(75); break; default: sortBy = $scope._viewRouteParams().sort; break; } } var curPage = (typeof $scope._viewRouteParams().page !== 'undefined') ? $scope._viewRouteParams().page : 1; if ($scope.loadTime > 1) { curPage = $scope.loadTime; } var dataSend = { 'cur_page': curPage, 'per_page': (typeof $scope._viewRouteParams().per_page !== 'undefined') ? $scope._viewRouteParams().per_page : 12, 'txt_sortby': sortBy, 'txt_filter_json': JSON.stringify(option) }; /* Fetch Data */ GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok === 1) { /*if(e.data.dataList.length > 0){ $scope.productArray = e.data.dataList; $scope.buildPaginationParameter(e.data); } */ if (e.ok === 1 && !$scope.productArray.length) { $scope.productArray = e.data.dataList; $scope.all_item = e.data.total_rows; console.log("sdjksiodjsds : 0", $scope.all_item, $scope.productArray); if ($scope.all_item <= $scope.productArray.length) { $scope.set_loadmore = false; } } else { if (e.data.dataList.length) { var currentData = $scope.productArray; $scope.productArray = currentData.concat(e.data.dataList); $scope.all_item = e.data.total_rows; console.log("sdjksiodjsds : 1", $scope.all_item, $scope.productArray); if ($scope.all_item <= $scope.productArray.length) { $scope.set_loadmore = false; } } else if ($scope.loadTime > 1 && !e.data.dataList.length) { $scope.loadNoMore = true; } } /*console.log("productArray", $scope.productArray);*/ if ($("#feature-product").hasClass('hide')) { $('#feature-product').removeClass('hide'); } } $scope.productState.load = false; $scope.productState.done = true; console.log("Share Component Get All", dataSend, option, e); }); }; $scope.getProduct(); /* Build pagination parameter * @params data (product return data) * @return objectArray */ $scope.pagination_data = {}; $scope.buildPaginationParameter = function(data) { if (data === false) { $scope.pagination_data = {}; return; } var generateRangeArray = function(total_items, per_page, cur_page) { console.log("generateRangeArray", total_items, per_page, cur_page); var returnPageArray = []; var size = 5; var totalPage = Math.ceil(total_items / per_page); var start = cur_page; if (totalPage <= size) { for (var i = 0; i < totalPage; i++) { returnPageArray.push(i + 1); } } else { if (start <= size) { for (var i = 0; i < size; i++) { returnPageArray.push(i + 1); } } else { if (start >= 1) { var maxPage = (start - 1) + size; } else { var maxPage = start + size; } if (maxPage >= totalPage) { maxPage = totalPage; start = (maxPage - size) + 1; } for (var i = start - 1; i < maxPage; i++) { returnPageArray.push(i + 1); } } } return returnPageArray; }; $scope.pagination_data.cur_page = parseInt(data.cur_page); $scope.pagination_data.per_page = parseInt(data.per_page); $scope.pagination_data.result_rows = parseInt(data.result_rows); $scope.pagination_data.total_rows = parseInt(data.total_rows); $scope.pagination_data.max_page = Math.ceil($scope.pagination_data.total_rows / $scope.pagination_data.per_page); $scope.pagination_data.prev_page = parseInt($scope.pagination_data.cur_page - 1); $scope.pagination_data.next_page = parseInt($scope.pagination_data.cur_page + 1); $scope.pagination_data.page_array = generateRangeArray($scope.pagination_data.total_rows, $scope.pagination_data.per_page, $scope.pagination_data.cur_page); console.log('$scope.pagination_data', $scope.pagination_data); }; /** * select listener (sortby) * @params model (string) * @return event */ $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('search-result') !== -1) ? '/search-result' : '/search-result'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; $scope.productListOnSortChange1 = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('search-result') !== -1) ? '/search-result' : '/search-result'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().tagname != 'undefined' && $location.search().tagname != "") { otherParams += "&tagname=" + $location.search().tagname; paramsObj.tagname = $location.search().tagname; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope.productState.load = false; $scope.productState.done = true; /*if($scope.checkSeo()){ $location.path(pathStr).search(paramsObj); } else { window.location.href = pathStr + "?sort=" + sortbyModel + otherParams; }*/ $location.path(pathStr).search(paramsObj); }, 300); }; /** * select listener (item per page) * @params model (string) * @return event */ $scope.displayChange = function(e) { if (window.location.href.indexOf('search-result') !== -1) { $location.path("/search-result").search({ 'page': 1, 'per_page': e }); } else { $location.path("/search-result").search({ 'page': 1, 'per_page': e });; } }; $scope.buildFilterUrl = function(exceptionalKey) { var a = ''; angular.forEach($routeParams, function(item, key) { if (key !== 'page' && key !== exceptionalKey) a += "&" + key + "=" + item; }); return a; }; $scope.displayInt = function(i) { return parseInt(i) || false; }; $scope.printSelected = function(a) { if ($routeParams.sort == a) { return " selected"; } return " "; }; $scope.checkColorConfig = function() { return ($('config-color').length) ? true : false; }; $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; $scope.titleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* when route change success => do something */ $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { console.log("pageChangedSuccess", current); if ($scope.loadTime > 1) { $scope.loadTime = 1; } $scope.getProduct(); if (!$scope.categoryArray.length && !$scope.categoryLoad.length) { $scope.getReferral(); } $scope.buildCatgegoryMobile(); }); /* FIlter FORM */ $scope.viewType = 'grid'; $scope._filter = $scope._viewRouteParams().filter_data; $scope.filterBrandModel = []; $scope.filter_brand = []; $scope.$watch('_filter', function(newValue, oldValue) { if (!newValue) return; var a = newValue.split('|'); for (var i = 0; i < a.length; i++) { var b = a[i].split('@'); if (b[0] == 'brand') { var c = b[1].split(','); for (var ii = 0; ii < c.length; ii++) { $scope.filter_brand.push(parseInt(c[ii])); } } console.log('filter_brand', $scope.filter_brand); } }); $scope.checkFilterBrand = function(val) { return ($scope.filter_brand.indexOf(parseInt(val)) !== -1) ? true : false; }; $scope.checkFilterBrandChange = function(val, isSelect) {}; /* Button to load more */ $scope.loadMore = function() { $scope.loadTime = $scope.loadTime + 1; $timeout(function() { $scope.getProduct(); }, 200); }; $scope.loadMore1 = function() { $scope.loadTime1 = $scope.loadTime1 + 1; $timeout(function() { $scope.getTagarray($scope.tag_name, $scope.loadTime1); }, 200); }; $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel, '1'); console.log("test_array :", $scope.invited); } }; }; return promise; }); _ui_share_app.directive('productSearchPageF', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productSearchPageF'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { }; $scope.doFilterBy = function(isChecked, badgeId) { }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } if (typeof $routeParams.search !== 'undefined' && $routeParams.search != '') { /* check if array */ json_filter.search = $routeParams.search; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } console.log("json_filter.referral_id_array_in :" , json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* search-result name of this search-result */ search: $scope.viewRouteParams().search, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.search !== 'undefined' && path.search !== "") { strHref += '?search=' + path.search; } else { delete path.search; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); // if($(window).height() > 595){ // $('.erere').css('min-height',(($(window).height() - 145)+'px')); // // alert($(window).height() - 145); // } }; return promise; }); _ui_share_app.directive('productSearchPageFb', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productSearchPageFb'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; $('div#slider-range').slider({ range: true, min: 0, max: 100000, step: 500, values: [0, 10000], slide: function(event, ui) { $scope.$apply(function() { $scope.rangeConfig.min = parseInt(ui.values[0]); $scope.rangeConfig.max = parseInt(ui.values[1]); }); } }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { }; $scope.doFilterBy = function(isChecked, badgeId) { }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } if (typeof $routeParams.search !== 'undefined' && $routeParams.search != '') { /* check if array */ json_filter.search = $routeParams.search; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } console.log("json_filter.referral_id_array_in :" , json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* search-result name of this search-result */ search: $scope.viewRouteParams().search, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'category-lists'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.search !== 'undefined' && path.search !== "") { strHref += '?search=' + path.search; } else { delete path.search; /*strHref += '?root_id=0';*/ } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); // if($(window).height() > 595){ // $('.erere').css('min-height',(($(window).height() - 145)+'px')); // // alert($(window).height() - 145); // } }; return promise; }); _ui_share_app.directive('productSearchPageFc', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productSearchPageFc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component' }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; // $('div#slider-range').slider({ // range: true, // min: 0, // max: 100000, // step: 500, // values: [0, 10000], // slide: function(event, ui) { // $scope.$apply(function() { // $scope.rangeConfig.min = parseInt(ui.values[0]); // $scope.rangeConfig.max = parseInt(ui.values[1]); // }); // } // }); /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { // $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '8'; $scope.changefilterPerPageData = function() { // $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { // $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { }; $scope.doFilterBy = function(isChecked, badgeId) { }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { /*$scope.filter_category = what;*/ $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { // $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } if (typeof $routeParams.search !== 'undefined' && $routeParams.search != '') { /* check if array */ json_filter.search = $routeParams.search; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = refOArray; } } console.log("json_filter.referral_id_array_in :" , json_filter.referral_id_array_in); var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 8, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* search-result name of this search-result */ search: $scope.viewRouteParams().search, /* category name of this category */ badge: badgeIdArray, /* view of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'search-result'; // if (typeof path.root_id !== 'undefined' && path.root_id !== "") { // strHref += '?root_id=' + path.root_id; // } else { // delete path.root_id; /*strHref += '?root_id=0';*/ // } if (typeof path.search !== 'undefined' && path.search !== "") { strHref += '?search=' + path.search; } else { delete path.search; /*strHref += '?root_id=0';*/ } // if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { // strHref += '&referral_id=' + path.referral_id; // } else { // delete path.referral_id; // } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } // if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { // strHref += '&referral_name=' + path.referral_name; // } else { // delete path.referral_name; // } // if (typeof path.badge !== 'undefined' && path.badge !== "") { // strHref += '&badge=' + path.badge.join(",").toString(); // } else { // delete path.badge; // } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("result?") == -1) { strHref = strHref.replace("search-result&", "search-result?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); // if($(window).height() > 595){ // $('.erere').css('min-height',(($(window).height() - 145)+'px')); // // alert($(window).height() - 145); // } }; return promise; }); _ui_share_app.directive('productSearchPageG', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productSearchPageG'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', cartitem: '@cartitem', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_price_desc'; $scope.changeFilterSortData = function() { // $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '10'; $scope.changefilterPerPageData = function() { // $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type){ $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { // $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) { }; $scope.doFilterBy = function(isChecked, badgeId) { }; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { // $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d,$scope).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d , $scope).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d , $scope).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } if (typeof $routeParams.search !== 'undefined' && $routeParams.search != '') { /* check if array */ json_filter.search = $routeParams.search; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } /* check sort */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 10, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend , $scope).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* search-result name of this search-result */ search: $scope.viewRouteParams().search, /* category name of this category */ badge: badgeIdArray, /* view name of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'search-result'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.search !== 'undefined' && path.search !== "") { strHref += '?search=' + path.search; } else { delete path.search; /*strHref += '?root_id=0';*/ } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; // var properHeight = ($('.erere').height()); if($(window).height() > 595){ $('.erere').css('min-height',(($(window).height() - 145)+'px')); // alert($(window).height() - 145); } angular.element($window).bind('scroll', function() { var curPos = ($(document).scrollTop()); var properHeight = ($('.erere').height()); console.debug("Cur pos", curPos, properHeight); if($(window).width() > 991){ if ((curPos + ($(window).height() - 145)) > properHeight ) { if ((properHeight - curPos) <= ($(window).height() - 145)) { if(properHeight - ($(window).height() - 145) < 0){ /* document.getElementsByClassName('testrewq')[0].style.top = "0px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = "0px"; */ $('.testrewq').css('top','0px'); $('.testrewq').css('margin-bottom','0px'); }else{ $('.testrewq').css('top',(properHeight - ($(window).height() - 145)) + 'px'); $('.testrewq').css('margin-bottom',(properHeight - ($(window).height() - 145)) + 'px'); /* document.getElementsByClassName('testrewq')[0].style.top = (properHeight - ($(window).height() - 145)) + "px"; document.getElementsByClassName('testrewq')[0].style.marginBottom = (properHeight - ($(window).height() - 145)) + "px"; */ } } else { $('.testrewq').css('top','auto'); /* document.getElementsByClassName('testrewq')[0].style.top = "auto"; */ } angular.element('.testrewq').addClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').addClass('unactive'); } } else { $('.testrewq').css('top','auto'); /* document.getElementsByClassName('testrewq')[0].style.top = "auto"; */ angular.element('.testrewq').removeClass('unactive'); if ($(window).width() > 991) { angular.element('.bottom-buy-overlay').removeClass('unactive'); } } }else{ angular.element('.testrewq').removeClass('unactive'); } }); }; return promise; });_ui_share_app.directive('productSearchPageH', function($rootScope, $routeParams, $location, shareService) { var templateName = 'productSearchPageH'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.assetsPath = 'extensions/themes/assets/'; function removeValueInArray(arr) { var what, a = arguments, L = a.length, ax; while (L > 1 && arr.length) { what = a[--L]; while ((ax = arr.indexOf(what)) !== -1) { arr.splice(ax, 1); } } return arr; } $scope.buildTitleUrl = function(str) { var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return s; }; /* view route params */ $scope.viewRouteParams = function() { return $routeParams || false; }; /* filter price */ $scope.rangeConfig = { min: 0, max: 100000 }; /* filter Sort */ $scope.filterSortData = $scope.viewRouteParams().sort || 'product_lastest_create'; $scope.changeFilterSortData = function() { // $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; /* filter perpage */ $scope.filterPerPageData = $scope.viewRouteParams().perpage || '50'; $scope.changefilterPerPageData = function() { // $('#myModal4').modal('hide'); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.viewTypeSet = function(view_type) { $scope.viewType = view_type; $timeout(function() { $scope.pathChange(); }, 300); }; /* filter by */ $scope.filter_new = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(72) !== -1) ? true : false; $scope.filter_rec = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(74) !== -1) ? true : false; $scope.filter_best = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(75) !== -1) ? true : false; $scope.filter_fea = (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge.indexOf(16) !== -1) ? true : false; $scope.filterByData = []; $scope.changeLeftFilterBy = function(isChecked, badgeId) { $('#myModal3').modal('hide'); console.log("changeLeftFilterBy: filter_new", $scope.filter_new); console.log("changeLeftFilterBy: filter_rec", $scope.filter_rec); console.log("changeLeftFilterBy: filter_best", $scope.filter_best); console.log("changeLeftFilterBy: filter_fea", $scope.filter_fea); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.checkFilterBy = function(v) {}; $scope.doFilterBy = function(isChecked, badgeId) {}; /* Filter by Category */ $scope.filter_category = 0; $scope.filterCat = $scope.viewRouteParams().referral_id || 0; $scope.doCategoryChange = function(isChecked, refId) { $scope.filterCat = refId; $timeout(function() { $scope.pathChange(); }, 300); }; /* Filter by brand */ $scope.filter_brand = []; $scope.doBrandClick = function(index, isChecked, id) { var refId = parseInt(id); if (isChecked) { if ($scope.filter_brand.indexOf(refId) == -1) { $scope.filter_brand.push(refId); } } else { var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); } console.log("$scope.filter_brand : doBrandClick", isChecked, $scope.filter_brand); $timeout(function() { $scope.pathChange(); }, 300); }; $scope.doBrandCheck = function(id) { var refId = parseInt(id); if ($scope.filter_brand.indexOf(refId) == -1) { return false; } else { return true; } }; $scope.doBrandChange = function(isChecked, id) { console.log("$scope.filter_brand : doBrandChange", isChecked, id); $scope.doBrandClick(0, isChecked, id); }; $scope.doBrandSingleClick = function(isChecked, id) { $('#myModal2').modal('hide'); console.log("$scope.filter_brand : doBrandSingleClick", isChecked, id); if (isChecked == undefined || isChecked == false || !isChecked) { var refId = parseInt(id); var pos = $scope.filter_brand.indexOf(refId); $scope.filter_brand.splice(pos, 1); $timeout(function() { $scope.pathChange(); }, 300); } }; /* Get data category * @return array */ $scope.data_category_parent = false; $scope.data_category_parent_done = false; $scope.getDataCategoryParent = function() { var d = { 'txt_referral_id': $scope.viewRouteParams().root_id, }; GAEAPI.get('referral/id', d).then(function(e) { if (e.ok == 1) { $scope.data_category_parent = e.data; } $scope.data_category_parent_done = true; }); }; /* Get data category * @return array */ $scope.data_category = []; $scope.data_category_done = false; $scope.getDataCategory = function() { if ($scope.data_category.length <= 0) { var d = { 'txt_referral_type_id': 11, 'txt_parent_id': (typeof $routeParams.root_id != 'undefined' && $routeParams.root_id != '') ? $routeParams.root_id : 0, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_category = e.data; } $scope.data_category_done = true; }); } }; /* Get data brand * @return array */ $scope.data_brand = []; $scope.data_brand_done = false; $scope.getDataBrand = function() { if ($scope.data_brand.length <= 0) { var d = { 'txt_referral_type_id': 12, 'txt_sortby': 'referral_name_a-z', }; GAEAPI.get('referral/map', d).then(function(e) { if (e.ok == 1) { $scope.data_brand = e.data; } $scope.data_brand_done = true; }); } }; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope.getDataProduct(); }, 300); }; /* get data product */ $scope.data_product = []; $scope.data_product_done = false; $scope.fetchTime = 1; $scope.all_page = true; $scope.getDataProduct = function() { var dupplicateRemove = function(curArray, valueToCheck) { console.log("dupplicateRemove", curArray); /*return r;*/ var r = []; for (var i = 0; i < curArray.length; i++) { if (typeof curArray[i] !== 'undefined' && curArray[i].indexOf(valueToCheck) == -1) { r.push(curArray[i]); } } r.push(valueToCheck); return r; }; var json_filter = { badge_id_array: ["18"] }; /* Check Parent */ if (typeof $routeParams.referral_id !== 'undefined' && $routeParams.referral_id != '') { /* check if array */ var refArray = $routeParams.referral_id.split(','); json_filter.referral_id_array = ($routeParams.referral_id.indexOf(',') != -1 && refArray.length > 0) ? refArray : [$routeParams.referral_id]; } if (typeof $routeParams.search !== 'undefined' && $routeParams.search != '') { /* check if array */ json_filter.search = $routeParams.search; } /* check badge */ if (typeof $routeParams.badge !== 'undefined' && $routeParams.badge != '') { if ($routeParams.badge.indexOf(',') != -1) { var badgeArray = $routeParams.badge.split(','); var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat(badgeArray); json_filter.badge_id_array = dupplicateRemove(newBadge, "18"); } else { /*var oldBadge = json_filter.badge_id_array; var newBadge = oldBadge.concat($routeParams.badge); json_filter.badge_id_array = dupplicateRemove(newBadge, "18");*/ } } /* check other refferal */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } /* check sort */ if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array != '') { var refOArray = $routeParams.referral_array.split(','); if ($routeParams.referral_array.indexOf(',') != -1 && refOArray.length > 0) { json_filter.referral_id_array_in = refOArray; } else { json_filter.referral_id_array_in = [refOArray]; } } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': $scope.filterPerPageData || 50, 'txt_sortby': $scope.filterSortData, 'txt_filter_json': JSON.stringify(json_filter), }; console.log("Zoom: getDataProduct: dataSend", dataSend); if (CUR_THEME.shop_id() == "541") { $http.get("https://zoomcamera.getappeasy.com/store/api/v1/product/lists", { params: dataSend }).then(function(res) { console.log("Zoom: getDataProduct : Custom", res); var e = res.data; if (e.ok == 1) { if ($scope.data_product.length) { var properHeight = ($('.erere').height()); var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; var properHeight = ($('.erere').height()); } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } else { GAEAPI.get('product/lists', dataSend).then(function(e) { if (e.ok == 1) { if ($scope.data_product.length) { var curData = $scope.data_product; $scope.data_product = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , load more", e); } else { $scope.data_product = e.data.dataList; if (e.data.total_rows <= $scope.data_product.length) { $scope.all_page = false; } else { $scope.all_page = true; } $scope.data_product_done = true; console.log("Zoom: getDataProduct: e , new data", e); } } else if (!e.data.dataList.length) {} if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } }); } }; $scope.getDataCategory(); $scope.getDataCategoryParent(); $scope.getDataBrand(); $scope.getDataProduct(); $scope.viewType = $routeParams.view || 'grid'; /* list / grid */ /* Check if seo enable */ $scope.checkSeo = function() { return (GURL.isHtml5Mode()) ? true : false; }; /* check referral from url */ $scope.checkRef = function(id) { if (typeof $routeParams.referral_array !== 'undefined' && $routeParams.referral_array !== '') { if ($routeParams.referral_array.indexOf(id) !== -1) { return true; } } return false; }; /* string split */ $scope.stringDisplay = function(string, search, what) { return string.replace(search, what); }; /* return qty of product */ $scope.viewQuantity = function(productIdStr) { return parseInt($('input[data-id="' + productIdStr + '"]').val()) || 1; }; /* display badge id by string * @params {strBadge} string badge * @return string name */ $scope.displayBadgeIdByString = function(strBadge) { switch (strBadge) { case 'New Arrival': return 72; break; case 'Recommend': return 74; break; case 'Best Seller': return 75; break; case 'Featured': return 16; break; case 'Feature': return 16; break; } }; /* display string by badge id * @params {strBadge} string badge * @return string name */ $scope.displayBadgeStringByBadgeId = function(id) { var badgeIdInt = parseInt(id); switch (badgeIdInt) { case 72: return 'New Arrival'; break; case 74: return 'Recommend'; break; case 75: return 'Best Seller'; break; case 16: return 'Featured'; break; case 16: return 'Feature'; break; } }; $scope.pathChange = function() { var buildBadge = function() { var r = [18]; if ($scope.filter_new) { r.push(72); } if ($scope.filter_rec) { r.push(74); } if ($scope.filter_best) { r.push(75); } if ($scope.filter_fea) { r.push(16); } return r; }; var buildOtherReferral = function() {}; var badgeIdArray = buildBadge(); /*var otherReferralArray = buildOtherReferral();*/ var path = { root_id: $scope.viewRouteParams().root_id, /* parent category of this category */ referral_id: ($scope.filterCat != 0) ? $scope.filterCat : $scope.viewRouteParams().referral_id, /* product in this category/filter cat */ referral_name: $scope.viewRouteParams().referral_name, /* search-result name of this search-result */ search: $scope.viewRouteParams().search, /* category name of this category */ badge: badgeIdArray, /* view name of this view */ view: $scope.viewType, /* new arrival, recommend, best seller, featured product */ sort: $scope.filterSortData, /* sortby */ perpage: $scope.filterPerPageData, referral_array: $scope.filter_brand, }; var strHref = 'search-result'; if (typeof path.root_id !== 'undefined' && path.root_id !== "") { strHref += '?root_id=' + path.root_id; } else { delete path.root_id; /*strHref += '?root_id=0';*/ } if (typeof path.search !== 'undefined' && path.search !== "") { strHref += '?search=' + path.search; } else { delete path.search; /*strHref += '?root_id=0';*/ } if (typeof path.view !== 'undefined' && path.view !== "") { strHref += '&view=' + path.view; } else { delete path.view; } if (typeof path.referral_id !== 'undefined' && path.referral_id !== "") { strHref += '&referral_id=' + path.referral_id; } else { delete path.referral_id; } if (typeof path.referral_name !== 'undefined' && path.referral_name !== "") { strHref += '&referral_name=' + path.referral_name; } else { delete path.referral_name; } if (typeof path.badge !== 'undefined' && path.badge !== "") { strHref += '&badge=' + path.badge.join(",").toString(); } else { delete path.badge; } if (typeof path.sort !== 'undefined' && path.sort !== "") { strHref += '&sort=' + path.sort; } else { delete path.sort; } if (typeof path.perpage !== 'undefined' && path.perpage !== "") { strHref += '&perpage=' + path.perpage; } else { delete path.perpage; } if (typeof path.referral_array !== 'undefined' && path.referral_array.length > 0) { strHref += '&referral_array=' + path.referral_array.join(",").toString(); } else { delete path.referral_array; } /*console.log("pathChange", path); console.log("pathChange: strHref", strHref);*/ if (strHref.indexOf("lists?") == -1) { strHref = strHref.replace("category-lists&", "category-lists?"); } $location.url(strHref).replace(); $scope.$apply(); }; $scope.buildParamsBadge = function() { if (typeof $scope.viewRouteParams().badge !== 'undefined' && $scope.viewRouteParams().badge != "") { $scope.filterByData = []; if ($scope.viewRouteParams().badge.indexOf(',') == -1) { return; } var a = $scope.viewRouteParams().badge.split(","); for (var i = 0; i < a.length; i++) { var id = parseInt(a[i]); switch (id) { case 72: if (!$scope.filter_new) { $scope.filter_new = true; } break; case 74: if (!$scope.filter_rec) { $scope.filter_rec = true; } break; case 75: if (!$scope.filter_best) { $scope.filter_best = true; } break; case 16: if (!$scope.filter_fea) { $scope.filter_fea = true; } break; } } } }; $scope.buildParamsBrand = function() { if (typeof $scope.viewRouteParams().referral_array !== 'undefined' && $scope.viewRouteParams().referral_array != "") { $scope.filter_brand = []; if ($scope.viewRouteParams().referral_array.indexOf(',') == -1) { var idSingle = parseInt($scope.viewRouteParams().referral_array); if ($scope.filter_brand.indexOf(idSingle) == -1) { $scope.filter_brand.push(idSingle); } console.log("buildParamsBrand: single ", $scope.filter_brand); } else { var a = $scope.viewRouteParams().referral_array.split(","); if (a.length) { for (var i = 0; i < a.length; i++) { var idMultiple = parseInt(a[i]); if ($scope.filter_brand.indexOf(idMultiple) == -1) { $scope.filter_brand.push(idMultiple); } console.log("buildParamsBrand: idMultiple ", idMultiple, $scope.filter_brand); } } } } console.log("buildParamsBrand params", $scope.viewRouteParams().referral_array); console.log("buildParamsBrand: filter_brand", $scope.filter_brand); }; $scope.buildParamsBrand(); $rootScope.$on('$routeChangeStart', function(event, current, prev) { if ($scope.data_product_done && $scope.data_product.length) { $scope.data_product_done = false; $scope.data_product = []; } }); $rootScope.$on('$routeChangeSuccess', function(event, current, prev) { $scope.buildParamsBadge(); $scope.buildParamsBrand(); if (!$scope.data_product_done && !$scope.data_product.length) { $timeout(function() { $scope.getDataProduct(); }, 100); } }); /* Event Listener: referral/map */ $scope.display_category_data = []; $scope.display_category_data_done = false; /* get data from parent app */ if (shareService.get('referralMap') !== false) { $scope.display_category_data = shareService.get('referralMap'); $scope.display_category_data_done = true; console.log("referralMap", $scope.display_category_data); } else { console.log("referralMap : failed", $scope.display_category_data); GAEAPI.get('referral/map', { txt_referral_type_id: 11 }, $scope).then(function(e) { console.log("referralMap : request api", e.data); if (e.ok == 1) { $scope.display_category_data = e.data; $scope.display_category_data_done = true; } }); } $scope.invited = []; $scope.insertinvited = function(user) { if (user.isChecked[user.product_id]) { if (user.product_attribute.length != 0) { $scope.invited.push(user.product_id); if ($scope.invited.length > 4) { alert("no more 4 compare"); user.isChecked[user.product_id] = false; var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } else { console.log("test_array :", $scope.invited); } } else { alert("item can't compare"); user.isChecked[user.product_id] = false; } } else { var toDel = $scope.invited.indexOf(user); $scope.invited.splice(toDel); console.log("test_array :", $scope.invited); } }; }; return promise; });_ui_share_app.directive('productSearchPageMaeju', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageMaeju'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productSearchPageDa : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().brand || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { search: inRouteParams.search, referral_array: inRouteParams.referral_array, sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "search-result"; if (typeof data.search != 'undefined' && data.search !== "") { page += '?search=' + data.search; if (typeof data.referral_array != 'undefined' && data.referral_array !== "") { page += '&referral_array=' + data.referral_array; } else { delete data.referral_array; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; page += '&referral_type=' + 'category'; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [refOArray]; } } if (params.badge != undefined && params.badge != "") { txt_filter_json.badge_id_array = [18, params.badge]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json), 'from': moment().unix() }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); }); } }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [refOArray]; } } if (params.badge != undefined && params.badge != "") { txt_filter_json.badge_id_array = [18, params.badge]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); $scope.carArray = []; $scope.getData().getRouteParams(function(params) { var txt_filter_json = {}; var dataSend = { 'txt_referral_type_id': 11, 'txt_sortby': 'referral_sort_index_asc_name_asc', 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('referral/map', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(res) { $scope.carArray = res.data; }); }); }); }; return promise; });_ui_share_app.directive('productSearchPageObc', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageObc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.routeParams = function() { return $routeParams || false; }; $scope.viewType = 'grid'; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.all_page = true; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = {}; txt_filter_json.badge_id_array = [18]; txt_filter_json.search = $scope.routeParams().search; if (typeof $scope.routeParams().referral_array !== 'undefined' && $scope.routeParams().referral_array != '') { var refOArray = $scope.routeParams().split(','); if ($scope.routeParams().indexOf(',') != -1 && refOArray.length > 0) { txt_filter_json.referral_id_array_in = refOArray; } else { txt_filter_json.referral_id_array_in = refOArray; } } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 40, 'txt_sortby': $scope.productListSort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; console.log("product/lists : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { if ($scope._dataArray.length) { var curData = $scope._dataArray; $scope._dataArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } else { $scope._dataArray = e.data.dataList; if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } // $scope.data_product_done = true; // console.log("Zoom: getDataProduct: e , new data", e); } // $scope._dataArray = e.data.dataList; } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.fetchTime = 1; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope._getDataArray(); }, 300); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().badge || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { search: inRouteParams.search, sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "search-result"; if (typeof data.search != 'undefined' && data.search !== "") { page += '?search=' + data.search; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('productSearchPageSca', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageSca'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', cardgrid: '@cardgrid', cardlist: '@cardlist', databutton: '@databutton', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope._databutton = ($scope.databutton != undefined && $scope.databutton != 'undefined' && $scope.databutton != '') ? $scope.databutton : 'border_button_small'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productSearchPageSca : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_lastest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().brand || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { search: inRouteParams.search, referral_array: inRouteParams.referral_array, sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "search-result"; if (typeof data.search != 'undefined' && data.search !== "") { page += '?search=' + data.search; if (typeof data.referral_array != 'undefined' && data.referral_array !== "") { page += '&referral_array=' + data.referral_array; } else { delete data.referral_array; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; page += '&referral_type=' + 'category'; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [refOArray]; } } if (params.badge != undefined && params.badge != "") { txt_filter_json.badge_id_array = [18, params.badge]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json), 'from': moment().unix() }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); }); } }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.cover_top = params.search; $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [refOArray]; } } if (params.badge != undefined && params.badge != "") { txt_filter_json.badge_id_array = [18, params.badge]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); }; return promise; });_ui_share_app.directive('productSearchPageSk', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageSk'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', cardgrid: '@cardgrid', cardlist: '@cardlist', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productSearchPageSk : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_lastest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().brand || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { search: inRouteParams.search, referral_array: inRouteParams.referral_array, sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "search-result"; if (typeof data.search != 'undefined' && data.search !== "") { page += '?search=' + data.search; if (typeof data.referral_array != 'undefined' && data.referral_array !== "") { page += '&referral_array=' + data.referral_array; } else { delete data.referral_array; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; page += '&referral_type=' + 'category'; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [refOArray]; } } if (params.badge != undefined && params.badge != "") { txt_filter_json.badge_id_array = [18, params.badge]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json), 'from': moment().unix() }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); }); } }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 9, total_rows: 0 }; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.cover_top = params.search; $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); }; return promise; });_ui_share_app.directive('productSearchPageSkh', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageSkh'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', cardgrid: '@cardgrid', cardlist: '@cardlist', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productSearchPageSkh : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_lastest_create'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().brand || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { search: inRouteParams.search, referral_array: inRouteParams.referral_array, sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "search-result"; if (typeof data.search != 'undefined' && data.search !== "") { page += '?search=' + data.search; if (typeof data.referral_array != 'undefined' && data.referral_array !== "") { page += '&referral_array=' + data.referral_array; } else { delete data.referral_array; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; page += '&referral_type=' + 'category'; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [refOArray]; } } if (params.badge != undefined && params.badge != "") { txt_filter_json.badge_id_array = [18, params.badge]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json), 'from': moment().unix() }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); }); } }; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.getData().getRouteParams(function(params) { $scope.cover_top = params.search; $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [refOArray]; } } if (params.badge != undefined && params.badge != "") { txt_filter_json.badge_id_array = [18, params.badge]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); }; return promise; });_ui_share_app.directive('productSearchPageStyle', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageStyle'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function() { var getFunction = { consoleLog: function(name, data) { console.log('productSearchPageStyle : ', name, data); }, getRouteParams: function(callback) { var params = $routeParams; callback(params); }, stateData: function(loadIn, doneIn) { var _self = this; _self.consoleLog("getData : ", "------- stateData -------"); _self.consoleLog("getData : loadIn : ", loadIn); _self.consoleLog("getData : doneIn : ", doneIn); _self.consoleLog("getData : ", "------- stateData -------"); var state = { load: loadIn, done: doneIn }; return state; }, dataSend: function(api, dataSend, callback) { var _self = this; _self.consoleLog("getData : ", "------- dataSend -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : ", "------- dataSend -------"); callback(api, dataSend); }, getApi: function(api, dataSend, callback) { var _self = this; GAEAPI.get(api, dataSend, $scope).then(function(output) { _self.consoleLog("getData : ", "------- getApi -------"); _self.consoleLog("getData : api : ", api); _self.consoleLog("getData : dataSend : ", dataSend); _self.consoleLog("getData : output : ", output); _self.consoleLog("getData : ", "------- getApi -------"); callback(output); }); }, titleUrl: function(str) { var url = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); return url; }, locationUrl: function(template, data) { $location.url(template + data).replace(); }, main: function() { var _self = this; } } return getFunction; }; $scope.routeParams = function() { return $routeParams || false; }; $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { console.log("setDataSort sortData : ", input); $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { console.log("setDataBadge badgeData : ", input); $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().brand || ''; $scope.setDataBrand = function(input) { console.log("setDataBrand badgeData : ", input); $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { console.log("setShowProduct showProduct : ", input); $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().referral_id_map || ''; $scope.setReferralIdMapData = function(input) { console.log("setReferralIdMapData referralIdMapData : ", input); $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { search: inRouteParams.search, referral_array: inRouteParams.referral_array, sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, brand: $scope.brandData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; console.log("pageAndData data : ", data); var page = "search-result"; if (typeof data.search != 'undefined' && data.search !== "") { page += '?search=' + data.search; if (typeof data.referral_array != 'undefined' && data.referral_array !== "") { page += '&referral_array=' + data.referral_array; } else { delete data.referral_array; } if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.brand != 'undefined' && data.brand !== "") { page += '&brand=' + data.brand; } else { delete data.brand; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; $scope.setDataCategories = function(input) { $scope.categoriesData = input; var page = "category-lists"; if (typeof $scope.categoriesData != 'undefined' && $scope.categoriesData !== "") { page += '?root_id=' + '0'; page += '&referral_id=' + $scope.categoriesData; page += '&referral_type=' + 'category'; } else { delete $scope.categoriesDat; } $location.url(page).replace(); }; $scope.loadMore = function() { if ($scope.dataArrayPageState.load != true) { $scope.dataArrayPageState.load = true; $scope.dataArrayPageState.cur_page++; $scope.getData().getRouteParams(function(params) { $scope.search = params.search; var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [refOArray]; } } if (params.badge != undefined && params.badge != "") { txt_filter_json.badge_id_array = [18, params.badge]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json), 'from': moment().unix() }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { if ($scope.dataArray.length < output.data.total_rows) { var oldData = $scope.dataArray; $scope.dataArray = oldData.concat(output.data.dataList); $scope.dataArrayPageState.total_rows = output.data.total_rows; } else { $scope.dataArrayPageState.cur_page--; } $scope.dataArrayPageState.load = false; }); }); }); } }; $scope.search = ""; $scope.dataArrayPageState = { load: false, done: false, cur_page: 1, per_page: 12, total_rows: 0 }; $scope.dataArray = []; $scope.dataArrayState = $scope.getData().stateData(false, false); $scope.data_api = { shop_current: { data_send: {}, api: "shop/current", ok: false, data_array: [], data_array_state: { load: false, done: false } } }; $scope.getData().dataSend($scope.data_api.shop_current.api, $scope.data_api.shop_current.data_send, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.data_api.shop_current.data_array = output.data; }); }); $scope.getData().getRouteParams(function(params) { $scope.search = params.search; $scope.dataArrayState = $scope.getData().stateData(true, false); var txt_filter_json = {}; txt_filter_json.search = params.search; txt_filter_json.badge_id_array = [18]; if (params.referral_array != undefined && params.referral_array != "") { if (params.referral_array.indexOf(',') != -1) { txt_filter_json.referral_id_array_in = params.referral_array.split(','); } else { txt_filter_json.referral_id_array_in = [refOArray]; } } if (params.badge != undefined && params.badge != "") { txt_filter_json.badge_id_array = [18, params.badge]; } var dataSend = { 'cur_page': $scope.dataArrayPageState.cur_page, 'per_page': $scope.dataArrayPageState.per_page, 'txt_sortby': $scope.sortData, 'txt_filter_json': JSON.stringify(txt_filter_json) }; $scope.getData().dataSend('product/lists', dataSend, function(api, dataSend) { $scope.getData().getApi(api, dataSend, function(output) { $scope.dataArray = output.data.dataList; $scope.dataArrayPageState.total_rows = output.data.total_rows; $scope.dataArrayState = $scope.getData().stateData(false, true); }); }); }); }; return promise; });_ui_share_app.directive('productSearchPageVono', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageVono'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.routeParams = function() { return $routeParams || false; }; $scope.viewType = 'grid'; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.all_page = true; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = {}; txt_filter_json.badge_id_array = [18]; txt_filter_json.search = $scope.routeParams().search; if (typeof $scope.routeParams().referral_array !== 'undefined' && $scope.routeParams().referral_array != '') { var refOArray = $scope.routeParams().split(','); if ($scope.routeParams().indexOf(',') != -1 && refOArray.length > 0) { txt_filter_json.referral_id_array_in = refOArray; } else { txt_filter_json.referral_id_array_in = refOArray; } } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 40, 'txt_sortby': $scope.productListSort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { if ($scope._dataArray.length) { var curData = $scope._dataArray; $scope._dataArray = curData.concat(e.data.dataList); angular.forEach($scope._dataArray, function(item, index) { $scope.getNameUrl($scope._dataArray[index].product_title, function(res_title) { $scope._dataArray[index].product_title_url = res_title; }); }); if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } else { $scope._dataArray = e.data.dataList; angular.forEach($scope._dataArray, function(item, index) { $scope.getNameUrl($scope._dataArray[index].product_title, function(res_title) { $scope._dataArray[index].product_title_url = res_title; }); }); if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.getNameUrl = function(name, callback) { var _self = this; name = name.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--", "-"); callback(name); }; $scope.fetchTime = 1; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope._getDataArray(); }, 300); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); $scope.sortData = $scope.routeParams().sort || 'product_update_time_desc'; $scope.setDataSort = function(input) { $scope.sortData = input; $scope.pageAndData(); }; $scope.badgeData = $scope.routeParams().badge || ''; $scope.setDataBadge = function(input) { $scope.badgeData = input; $scope.pageAndData(); }; $scope.brandData = $scope.routeParams().badge || ''; $scope.setDataBrand = function(input) { $scope.brandData = input; $scope.pageAndData(); }; $scope.showProduct = 'grid'; $scope.setShowProduct = function(input) { $scope.showProduct = input; }; $scope.referralIdMapData = $scope.routeParams().badge || ''; $scope.setReferralIdMapData = function(input) { $scope.referralIdMapData = input; $scope.pageAndData(); }; $scope.pageAndData = function() { var inRouteParams = $scope.routeParams(); var data = { search: inRouteParams.search, sendtag: inRouteParams.sendtag, status: inRouteParams.status, root_id: inRouteParams.root_id, referral_id: inRouteParams.referral_id, referral_type: 'category', sort: $scope.sortData, badge: $scope.badgeData, badge_id: inRouteParams.badge_id, referral_id_map: $scope.referralIdMapData }; var page = "search-result"; if (typeof data.search != 'undefined' && data.search !== "") { page += '?search=' + data.search; if (typeof data.sort != 'undefined' && data.sort !== "") { page += '&sort=' + data.sort; } else { delete data.sort; } if (typeof data.badge != 'undefined' && data.badge !== "") { page += '&badge=' + data.badge; } else { delete data.badge; } } $location.url(page).replace(); }; }; return promise; });_ui_share_app.directive('productSearchPageWc', function($rootScope, $routeParams, $location) { var templateName = 'productSearchPageWc'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', margin: '@margin', component: '@component', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $window, $http) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.viewType = 'grid'; $scope._viewRouteParams = function() { return $routeParams || false; }; $scope.productListSort = $scope._viewRouteParams().sort || ""; $scope.productListOnSortChange = function(sortbyModel) { var otherParams = ''; var paramsObj = {}; var pathStr = (window.location.href.indexOf('search-result') !== -1) ? '/search-result' : '/search-result'; if (typeof $location.search().search != 'undefined' && $location.search().search != "") { otherParams += "&search=" + $location.search().search; paramsObj.search = $location.search().search; } if (typeof $location.search().referral_id != 'undefined' && $location.search().referral_id != "") { otherParams += "&referral_id=" + $location.search().referral_id; paramsObj.referral_id = $location.search().referral_id; } if (typeof $location.search().root_id != 'undefined' && $location.search().root_id != "") { otherParams += "&root_id=" + $location.search().root_id; paramsObj.root_id = $location.search().root_id; } if (typeof $location.search().referral_type != 'undefined' && $location.search().referral_type != "") { otherParams += "&referral_type=" + 'category'; paramsObj.referral_type = 'category'; } paramsObj.sort = sortbyModel; $timeout(function() { $scope.productListSort = sortbyModel; $scope.pagination_data = {}; $scope.productArray = []; $scope._dataArray = []; $location.path(pathStr).search(paramsObj); }, 300); }; $scope.set_viewtype = function(set_item) { $scope.viewType = set_item; }; $scope._dataArray = []; $scope._dataArrayState = { load: false, done: false }; $scope.all_page = true; $scope._getDataArray = function() { $scope._dataArrayState = $scope.StateData(true, false); var txt_filter_json = {}; txt_filter_json.badge_id_array = [18]; txt_filter_json.search = $scope._viewRouteParams().search; if (typeof $scope._viewRouteParams().referral_array !== 'undefined' && $scope._viewRouteParams().referral_array != '') { var refOArray = $scope._viewRouteParams().split(','); if ($scope._viewRouteParams().indexOf(',') != -1 && refOArray.length > 0) { txt_filter_json.referral_id_array_in = refOArray; } else { txt_filter_json.referral_id_array_in = refOArray; } } var dataSend = { 'cur_page': $scope.fetchTime, 'per_page': 40, 'txt_sortby': $scope.productListSort, 'txt_filter_json': JSON.stringify(txt_filter_json) }; console.log("product/lists : dataSend : ", dataSend); GAEAPI.get('product/lists', dataSend, $scope).then(function(e) { if (e.ok == 1) { if ($scope._dataArray.length) { var curData = $scope._dataArray; $scope._dataArray = curData.concat(e.data.dataList); if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } } else { $scope._dataArray = e.data.dataList; if (e.data.total_rows <= $scope._dataArray.length) { $scope.all_page = false; } else { $scope.all_page = true; } // $scope.data_product_done = true; // console.log("Zoom: getDataProduct: e , new data", e); } // $scope._dataArray = e.data.dataList; } if ($scope.fetchTime > 1) { $scope.loadMore_is_load = false; } $scope._dataArrayState = $scope.StateData(false, true); }); }; $scope.fetchTime = 1; /* Load More */ $scope.loadMore_is_load = false; $scope.loadMore = function() { $scope.fetchTime++; $scope.loadMore_is_load = true; $timeout(function() { $scope._getDataArray(); }, 300); }; $scope.StateData = function(_load_in, _done_in) { var State = { load: _load_in, done: _done_in }; return State; } $scope._getDataArray(); }; return promise; }); _ui_share_app.directive('promotionDetailPageTypeA', function ($rootScope, $routeParams) { var templateName = 'promotionDetailPageTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', promotionid: '@promotionid', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window, $location) { $scope.dataArray = []; $scope.getData = function(){ $scope.dataArray = []; var test = $scope.promotionid; var b = test.split("-"); var d = { "txt_promotion_id": b[0] }; GAEAPI.get('promotion/id', d, $scope).then(function(e){ if(e.ok === 1){ $scope.dataArray = e.data; } console.log('promotion',$scope.dataArray); }); }; $scope.getData(); $scope._getPostIdFromURL = function(){ var test = $scope.promotionid; var b = test.split("-"); return parseInt(b[0]); }; }; return promise; }); _ui_share_app.directive('promotionPageTypeA', function ($rootScope, $routeParams) { var templateName = 'promotionPageTypeA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', logo: '@logo', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.dataArray = []; $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.getData = function(){ $scope.dataArray = []; var d = { "cur_page": 1, "per_page": 20, "txt_filter_json": JSON.stringify({"type_number":7}) }; GAEAPI.get('promotion/lists', d, $scope).then(function(e){ if(e.ok === 1){ $scope.dataArray = e.data.dataList; } console.log('promotion',$scope.dataArray); }); }; $scope.getData(); $scope.promotionLinkByType=function(dataObject){ if (dataObject.promotion_type_number == 7) { if (dataObject.promotion_pdf.length) { GURL.location.href = dataObject.promotion_pdf[0].file_url; return; } } }; $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('promotionPageTypeB', function($rootScope, $routeParams) { var templateName = 'promotionPageTypeB'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', imgpath: '@imgpath', logo: '@logo', }; promise.link = function(scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function($scope, $timeout, $interval, $q, $window) { $scope.icnPath = CUR_THEME.file_url() + '../../assets/'; $scope.dataArray = []; $scope.dataArrayState = { load: false, done: false }; $scope.getData = function() { $scope.dataArray = []; $scope.dataArrayState.load = true; var d = { "cur_page": 1, "per_page": 20, "txt_filter_json": JSON.stringify({ "type_number": 7 }) }; GAEAPI.get('promotion/lists', d, $scope).then(function(e) { if (e.ok === 1) { $scope.dataArray = e.data.dataList; } console.log('promotion', $scope.dataArray); $scope.dataArrayState.load = false; $scope.dataArrayState.done = true; }); }; $scope.getData(); $scope.promotionLinkByType = function(dataObject) { if (dataObject.promotion_type_number == 7) { if (dataObject.promotion_pdf.length) { GURL.location.href = dataObject.promotion_pdf[0].file_url; return; } } }; $scope._showWeb = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function(objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; }; return promise; }); _ui_share_app.directive('promotionPageTypeC', function ($rootScope, $routeParams) { var templateName = 'promotionPageTypeC'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope.assetsPath = 'extensions/themes/assets/'; $scope.dataArray = []; $scope.dataDone = false; $scope.getData = function(){ $scope.dataArray = []; $scope.dataDone = false; var d = { "cur_page": 1, "per_page": 20, "txt_filter_json": JSON.stringify({"type_number":7}) }; GAEAPI.get('promotion/lists', d, $scope).then(function(e){ $scope.dataDone = true; if(e.ok === 1){ var dummy = []; for(var idx in e.data.dataList){ if($scope._showWeb(e.data.dataList[idx].promotion_badge)){ dummy.push(e.data.dataList[idx]); } } $scope.dataArray = dummy; } console.log('promotion',dummy); console.log('promotion',$scope.dataArray); }); }; $scope.getData(); $scope.promotionLinkByType=function(dataObject){ console.log("promotionLinkByType",dataObject); if (dataObject.promotion_type_number == 7) { if (dataObject.promotion_pdf.length) { window.location.href = dataObject.promotion_pdf[0].file_url; return; } else if(dataObject.promotion_image.length) { window.location.href = dataObject.promotion_image[0].image_url; return; } } }; $scope._showWeb = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 18) { r = true; break; } } return r; }; $scope._showApp = function (objArray) { var r = false; for (var i = 0; i < objArray.length; i++) { if (objArray[i].badge_id == 19) { r = true; break; } } return r; }; $scope.checkSeo=function(){ return (GURL.isHtml5Mode()) ? true : false; }; $scope.buildTitleUrl = function(str){ var s = str.replace(/[^a-zA-Zก-๙0-9 ]/g, "").split(" ").join("-").replace("--","-"); return s; }; }; return promise; }); _ui_share_app.directive('quotationPageA', function ($rootScope, $routeParams) { var templateName = 'quotationPageA'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { name: '@name', contact: '@contact', background: '@background', primary: '@primary', imgpath: '@imgpath', }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { /* Id */ $scope.product_id = $routeParams.product_id; /* Form Params */ $scope.input_email = ""; $scope.input_name = ""; $scope.input_tel = ""; $scope.input_message = ""; /* Form Validate */ $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_tel_valid = false; $scope.input_message_valid = false; /* Watch Value */ $scope.$watch('input_email', function(newValue, oldValue){ if(!newValue || newValue === ""){ $scope.input_email_valid = false; return; } if(!$scope.isEmail(newValue)){ $scope.input_email_valid = false; } else { $scope.input_email_valid = true; } }); $scope.$watch('input_name', function(newValue, oldValue){ if(!newValue || newValue === ""){ $scope.input_name_valid = false; return; } $scope.input_name_valid = true; }); $scope.$watch('input_tel', function(newValue, oldValue){ if(!newValue || newValue === "" ){ $scope.input_name_valid = false; return; } if(parseInt(newValue) > 0){ $scope.input_tel_valid = true; } else { $scope.input_tel_valid = false } }); $scope.$watch('input_message', function(newValue, oldValue){ if(!newValue || newValue === ""){ $scope.input_message_valid = false; return; } $scope.input_message_valid = true; }); /* Submit Data */ $scope.runTest = false; $scope.form_submit = function($event){ var submit = true; $scope.runTest = true; $($event.currentTarget).closest('form').find('[required]').each(function() { if ($(this).val() == '') { $(this).closest('.form_block').find('.after').addClass('error'); $(this).closest('.form_block').find('.round').addClass('error'); submit = false; }else { $(this).closest('.form-group').find('span').removeClass('error'); } }); var isPass = false; if(parseInt($('#contact_form input[name=input_tel]').val()) > 0 && $scope.isEmail($('#contact_form input[name="input_email"]').val())){ isPass = true; }else{ alert("กรุณากรอกอีเมล หรือ หมายเลขโทรศัพท์ ให้ถูกต้อง"); } if($scope.input_tel_valid == false){ $("input[name='input_tel']").addClass('error'); }else if(parseInt($('#contact_form input[name=input_tel]').val()) > 0){ $("[name='input_tel']").removeClass('error'); } if(!($scope.isEmail($('#contact_form input[name="input_email"]').val()))){ $("[name='input_email']").addClass('error'); }else{ $("[name='input_email']").removeClass('error'); } if($scope.name != "" && $scope.contact != "" && submit && isPass){ angular.element('#contact_form').hide(); angular.element('.contact_wait').show(); var formData = new FormData($('#contact_form')[0]); formData.append('input_owner_name',$scope.name); formData.append('input_owner_contact',$scope.contact); formData.append('input_product_id', $scope.quotationProduct[0].product_id); formData.append('input_product_name', $scope.quotationProduct[0].product_title); console.log("pass!", formData); $.ajax({ url: _ui_share_host + '../sendgrid/send-email-quotation.php', method: 'POST', data: formData, cache: false, contentType: false, processData: false, success: function (data, textStatus, jqXHR) { console.log("pass!",data); setTimeout(function(){ angular.element('.contact_wait').hide(); angular.element('.contact_error').hide(); angular.element('.contact_success').show(); },2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_tel = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_tel_valid = false; $scope.input_message_valid = false; $scope.runTest = false; }, error: function (jqXHR, textStatus, errorThrown) { setTimeout(function(){ angular.element('.contact_wait').hide(); angular.element('.contact_success').hide(); angular.element('.contact_error').show(); },2000); $scope.input_email = ""; $scope.input_name = ""; $scope.input_message = ""; $scope.input_tel = ""; $scope.input_email_valid = false; $scope.input_name_valid = false; $scope.input_tel_valid = false; $scope.input_message_valid = false; $scope.runTest = false; } }); } else { return; } }; /* Get Product */ $scope.quotationProduct = []; $scope.getProductId = function(id){ $scope.quotationProduct = []; var d = {'txt_product_id':id}; GAEAPI.get('product/id',d,$scope).then(function(e){ if(e.ok == 1){ $scope.quotationProduct.push(e.data); } }); }; /* Watch Product Id */ $scope.$watch('product_id',function(newValue, oldValue){ if(!newValue || newValue == 0){ return; } $scope.getProductId(newValue); }); $scope.isEmail = function(inputString){ var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(inputString); }; }; return promise; }); _ui_share_app.directive('testTextSlide', function ($rootScope, $routeParams) { var templateName = 'testTextSlide'; var templatePathUrl = _ui_share_host + templateName + '/' + templateName + '.html'; var promise = {}; promise.restrict = 'AE'; promise.scope = { }; promise.link = function (scope, element, attr) {}; promise.templateUrl = templatePathUrl; promise.transclude = true; promise.controller = function ($scope, $timeout, $interval, $q, $window) { $scope._textSlide = []; $scope._gettextslide = function(){ $scope._textslide_data = []; GAEAPI.get('web/home',{}).then(function(res){ if(res.ok == 1){ $scope._textSlide = res.data.textslide_banner; $scope.mkCarousel1('text_slider_container'); } console.log('_gettextslide', res); }); }; $scope._gettextslide(); $scope.mkCarousel1 = function(elem){ setTimeout(function(){ var carousel = $('.' + elem); var is_dark; carousel.not('.slick-initialized').slick({ autoplay:false, slidesToShow:1, dots:true }).addClass('active'); }, 1000); }; }; return promise; });