Advertisement
Guest User

Untitled

a guest
Nov 9th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 243.09 KB | None | 0 0
  1. 'use strict';
  2. angular.module('ngCart', ['ngCart.directives'])
  3. .config([
  4. function () {
  5.  
  6. }
  7. ])
  8. .provider('$ngCart', function () {
  9. this.$get = function () {
  10. };
  11. })
  12.  
  13. .run(['$rootScope', 'ngCart', 'ngCartItem', 'store', function ($rootScope, ngCart, ngCartItem, store) {
  14.  
  15. $rootScope.$on('ngCart:change', function () {
  16. //debugger
  17. ngCart.$save();
  18. });
  19.  
  20. if (angular.isObject(store.get('cart'))) {
  21. ngCart.$restore(store.get('cart'));
  22.  
  23. } else {
  24. ngCart.init();
  25. }
  26. }
  27. ])
  28. .config(['$httpProvider', function ($httpProvider) {
  29.  
  30. $httpProvider.interceptors.push('myHttpInterceptor');
  31.  
  32. }]).factory('myHttpInterceptor', ['$q', '$rootScope', function ($q, $rootScope) {
  33. var numRequests = 0;
  34. //var ajaxSpinner = $("#ajaxSpinner");
  35. var hide = function (r) {
  36. if (!--numRequests) {
  37. // ajaxSpinner.hide();
  38. $rootScope.disableBtn = true;
  39. }
  40. return r
  41. };
  42.  
  43. return {
  44. 'request': function (config) {
  45. numRequests++;
  46. // ajaxSpinner.show();
  47. $rootScope.disableBtn = false;
  48.  
  49. return config;
  50. },
  51.  
  52. 'response': function (response) {
  53. return hide(response);
  54. },
  55.  
  56. 'responseError': function (response) {
  57. return $q.reject(hide(response));
  58. }
  59. };
  60. }])
  61. .service('ngCart', [
  62. '$rootScope', 'ngCartItem', 'store', 'ngCart.lottoyard.api', 'Products', 'RaffleExpiresInMin', function ($rootScope, ngCartItem, store, LottoYardService, Products, RaffleExpiresInMin) {
  63.  
  64. this.init = function () {
  65. this.$cart = {
  66. shipping: 0,
  67. taxRate: 0,
  68. tax: 0,
  69. paymentMethodId: "",
  70. processor: "",
  71. fastProcessingTax: 0,
  72. amountToPay: 0,
  73. reedemCode: "",
  74. isFastProcessing: false,
  75. phoneOrEmail: "",
  76. iframePaymentMethods: [],
  77. currency: "",
  78. items: [],
  79. bonusAmountToUse: 0,
  80. useBonusmoney: false,
  81. evenLinesOnlyMessage: false
  82. };
  83. };
  84.  
  85. this.addItem = function (id, discount, groupComboBoxSelectionIndex, groupSettingsIndex, groupdiscount, groupnodraws, groupnoshares, grouporiginalprice,
  86. grouptotal, lotteryType, noofdraws, nooflines, numbers, originalprice, personalComboBoxSelectionIndex, personalSettingsIndex, selectedTab, totalCost,
  87. isSubscription, isQuickPick, ticketsNumbers, productType, productExpire, productIdSpecial, quantity, guid, isRaffle, olapCounterGuid, evenNumbersOnly) {
  88. var inCart = this.getItemById(id);
  89. debugger;
  90. if (typeof inCart === 'object') {
  91. //Update quantity of an item if it's already in the cart
  92. inCart.setQuantity(quantity, false);
  93. } else {
  94. if (this.$cart.items.length === 10) {
  95. //todo remove first element
  96. this.$cart.items.shift();
  97. }
  98.  
  99. discount = parseFloat(discount.toFixed(3));
  100. groupnodraws = parseInt(groupnodraws);
  101. groupnoshares = parseInt(groupnoshares);
  102.  
  103. if (selectedTab === 'single' && (typeof (productType) === 'undefined' || productType === "")) {
  104. productType = 1;
  105. groupSettingsIndex = undefined;
  106. } else if (selectedTab === 'groupselection' || selectedTab === "group") {
  107. productType = 3;
  108. personalSettingsIndex = undefined;
  109. }
  110.  
  111. if (productType === 3) {
  112. numbers = undefined;
  113. }
  114.  
  115. if (selectedTab === 'product' && productType === 3) {
  116. groupnoshares = groupnoshares === 0 ? 1 : groupnoshares;
  117. }
  118.  
  119. if (this.getIsFastProcessing()) {
  120. var isFastProcessing = true;
  121. //totalCost = parseFloat(totalCost) + this.getFastProcessingTax();
  122. }
  123.  
  124. if (personalSettingsIndex === 2 || groupSettingsIndex === 2) {
  125. isSubscription = true;
  126. } else {
  127. isSubscription = false;
  128. }
  129.  
  130. quantity = quantity > 0 ? quantity : 1;
  131. var rules;
  132. if (productType === 2 || productType === 4 || productType === 14 || productType === 19) {
  133. //14 and 19
  134. var product = LottoYardService.getProductById(productType);
  135. var productName = product.ProductName;
  136. var productRules = product.ValidLotteries.filter(function (obj) {
  137. if ('LotteryTypeId' in obj && typeof (obj.LotteryTypeId) === 'number' && obj.LotteryTypeId === lotteryType) {
  138. return true;
  139. }
  140. return false;
  141. })[0];
  142.  
  143. if (productType === 2 || productType === 4 || productType === 19) {
  144. if (quantity > 1) {
  145. totalCost = quantity * totalCost;
  146. }
  147. }
  148. if (productType === 2) {
  149. productName = LottoYardService.getLotteryById(lotteryType).LotteryType;
  150. }
  151. if (productType === 14 || productType === 19) {
  152. nooflines = 1;
  153. }
  154. if (productType === 19) {
  155. productName = "247Premium";
  156. }
  157. if (lotteryType === 7) {
  158. rules = {
  159. SelectNumbers: 0,
  160. MinSelectNumber: 0,
  161. MaxSelectNumbers: 0,
  162. ExtraNumbers: 0,
  163. MaxExtraNumbers: 0,
  164. MinExtraNumber: 0,
  165. DrawsPerWeek: 0
  166. };
  167. } else {
  168. rules = LottoYardService.getLotteryById(lotteryType);
  169. }
  170.  
  171. if (productType === 2 || productType === 4) {
  172.  
  173. nooflines = productRules.MinLines;
  174.  
  175. for (var i = 0; i < productRules.MinLines; i++) {
  176. if (i === productRules.MinLines - 1) {
  177. numbers += quickpick(rules);
  178. } else {
  179. numbers += quickpick(rules) + "|";
  180. }
  181. }
  182. }
  183.  
  184. var newItem = new ngCartItem(id, discount, groupComboBoxSelectionIndex, groupSettingsIndex, groupdiscount, groupnodraws, groupnoshares, grouporiginalprice,
  185. grouptotal, lotteryType, noofdraws, nooflines, numbers, originalprice, personalComboBoxSelectionIndex, personalSettingsIndex, selectedTab, totalCost, productName,
  186. rules.SelectNumbers, rules.MinSelectNumber, rules.MaxSelectNumbers, rules.ExtraNumbers, rules.MaxExtraNumbers, rules.MinExtraNumber, productRules.MinLines,
  187. productRules.MaxLines, rules.DrawsPerWeek, product.Draws, isFastProcessing, isSubscription, isQuickPick, ticketsNumbers, productType, productExpire, productIdSpecial, quantity, guid,
  188. isRaffle, olapCounterGuid);
  189.  
  190. } else {
  191. var lotteryname = LottoYardService.getLotteryById(lotteryType).LotteryType;
  192.  
  193. var rules = LottoYardService.getLotteryById(lotteryType);
  194.  
  195. if (selectedTab === 'product' || productType === 3) {
  196.  
  197. groupdiscount = 0;
  198.  
  199. angular.forEach(rules.ProductsDrawOptions, function (item) {
  200. if (item.ProductId === productType && item.IsSubscription === isSubscription) {
  201. angular.forEach(item.MultiDrawOptions, function (drawOpt) {
  202. if (drawOpt.NumberOfDraws === parseInt(groupnodraws)) {
  203. groupdiscount = drawOpt.Discount;
  204. }
  205. });
  206. }
  207. });
  208. }
  209.  
  210. if (productType === 1) {
  211. // debugger;
  212. originalprice = LottoYardService.getProductPriceByIds(productType, 1, lotteryType, 1).Price;
  213. noofdraws = parseInt(noofdraws);
  214. discount = 0;
  215. }
  216.  
  217. //getting MinLines and MaxLines accoring draws
  218.  
  219. //rules.ProductsDrawOptions - productId & IsSubscription
  220. // if (productType === 15 || productType === 24 || productType === 26 || productType === 31 || productType ===33) {
  221. if (typeof (ticketsNumbers) !== 'undefined' && ticketsNumbers.length > 0) {
  222. rules.MinLines = 1;
  223. rules.MaxLines = ticketsNumbers.length;
  224. isRaffle = true;
  225. } else {
  226. numbers = numbers ? linesChecker(numbers) : numbers;
  227. angular.forEach(rules.ProductsDrawOptions, function (item) {
  228. if (item.ProductId === productType && item.IsSubscription === isSubscription) {
  229. angular.forEach(item.MultiDrawOptions, function (drawOpt) {
  230. if (drawOpt.NumberOfDraws === parseInt(noofdraws)) {
  231. discount = drawOpt.Discount;
  232. rules.MinLines = drawOpt.MinLines;
  233. rules.MaxLines = drawOpt.MaxLines;
  234. }
  235. });
  236. }
  237. });
  238. if (productType === 1) {
  239. for (var j = nooflines; j < rules.MinLines; j++) {
  240. numbers += "|" + quickpick(rules);
  241. nooflines++;
  242. }
  243. totalCost = LottoYardService.getProductPriceByIds(productType, noofdraws, lotteryType, nooflines).Price;
  244. }
  245. }
  246.  
  247. var newItem = new ngCartItem(id, discount, groupComboBoxSelectionIndex, groupSettingsIndex, groupdiscount, groupnodraws, groupnoshares, grouporiginalprice,
  248. grouptotal, lotteryType, noofdraws, nooflines, numbers, originalprice, personalComboBoxSelectionIndex, personalSettingsIndex, selectedTab, totalCost, lotteryname,
  249. rules.SelectNumbers, rules.MinSelectNumber, rules.MaxSelectNumbers, rules.ExtraNumbers, rules.MaxExtraNumbers, rules.MinExtraNumber, rules.MinLines, rules.MaxLines, rules.DrawsPerWeek,
  250. rules.ProductsDrawOptions, isFastProcessing, isSubscription, isQuickPick, ticketsNumbers, productType, productExpire, productIdSpecial, quantity, guid, isRaffle, olapCounterGuid, evenNumbersOnly);
  251. }
  252.  
  253. if (newItem.getEvenLinesOnly() && newItem.getNumberOfLines() % 2 == 1) {
  254. sessionStorage.setItem('showEvenLinesOnly', true);
  255. $rootScope.$broadcast('ngCart:change', {});
  256. return;
  257. }
  258.  
  259. var items = this.$cart.items;
  260. var isAddedItem = false;
  261.  
  262. if (productType != 1 && productType != 3) {
  263. items.forEach(function (item) {
  264. if (item.getNumbers() && item.getNumbers() == newItem.getNumbers()) {
  265. isAddedItem = true;
  266. }
  267. })
  268. }
  269.  
  270. if (!isAddedItem) {
  271. this.$cart.items.push(newItem);
  272. }
  273.  
  274. $rootScope.$broadcast('ngCart:itemAdded', newItem);
  275. }
  276.  
  277. $rootScope.$broadcast('ngCart:change', {});
  278.  
  279. };
  280.  
  281.  
  282. this.addItemPredifined = function (productId, lotteryType, lines, draws, amount, guid, selectedNumbers, counterGuid) {
  283. // debugger;
  284. if (this.$cart.items.length === 10) {
  285. this.$cart.items.shift();
  286. }
  287. if (!isNumeric(productId)) {
  288. productId = parseInt(productId);
  289. }
  290.  
  291. if (!isNumeric(lotteryType)) {
  292. lotteryType = parseInt(lotteryType);
  293. }
  294.  
  295. if (!isNumeric(lines)) {
  296. lines = parseInt(lines);
  297. }
  298.  
  299. if (!isNumeric(draws)) {
  300. draws = parseInt(draws);
  301. }
  302.  
  303. if (!isNumeric(amount)) {
  304. amount = parseInt(amount);
  305. }
  306.  
  307. //generating id
  308. var productIdSpecial = 999;
  309. var product = LottoYardService.getProductById(productId);
  310. var productName,
  311. selectedTab,
  312. noofdraws,
  313. nooflines,
  314. rules,
  315. personalComboBoxSelectionIndex,
  316. personalSettingsIndex,
  317. isSubscription,
  318. isFastProcessing,
  319. isQuickPick,
  320. productExpire,
  321. ticketsNumbers,
  322. quanity;
  323.  
  324. var numbers = "";
  325. var quantity = 1;
  326. var isRaffle = false;
  327. productIdSpecial = 999;
  328. guid = guid;
  329.  
  330. if (typeof (product) === 'undefined') {
  331. productName = LottoYardService.getLotteryById(lotteryType).LotteryType;
  332. } else {
  333. productName = product.ProductName;
  334. selectedTab = 'product';
  335. }
  336.  
  337. if (productId === 3) {
  338. selectedTab = 'group';
  339. } else if (productId === 1) {
  340. selectedTab = 'personal';
  341. nooflines = parseInt(lines);
  342. } else if (draws === 0) {
  343. selectedTab = 'raffle';
  344. }
  345.  
  346. noofdraws = parseInt(draws);
  347.  
  348. var discount = 0,
  349. groupComboBoxSelectionIndex = 0,
  350. groupSettingsIndex = 0,
  351. groupdiscount = 0,
  352. groupnodraws = 0,
  353. groupnoshares = 0,
  354. grouporiginalprice = 0,
  355. grouptotal = 0;
  356.  
  357. var productType = productId;
  358. var originalprice = amount;
  359. var totalCost = amount;
  360.  
  361. rules = {
  362. SelectNumbers: 0,
  363. MinSelectNumber: 0,
  364. MaxSelectNumbers: 0,
  365. ExtraNumbers: 0,
  366. MaxExtraNumbers: 0,
  367. MinExtraNumber: 0,
  368. DrawsPerWeek: 0
  369. };
  370.  
  371. switch (selectedTab) {
  372. case 'personal':
  373. if (typeof selectedNumbers !== 'undefined') {
  374. numbers = linesChecker(selectedNumbers);
  375. } else {
  376. //get lottery rules for genereting lines
  377. rules = LottoYardService.getLotteryById(lotteryType);
  378. var minLines = rules.MinLines;
  379. var maxLines = rules.MaxLines;
  380.  
  381. if (nooflines > maxLines || minLines > nooflines) {
  382. throw "Lines can not be greater than max lines or less then defined in rules";
  383. }
  384. for (var i = 0; i < nooflines; i++) {
  385. if (i === nooflines - 1) {
  386. numbers += quickpick(rules);
  387. } else {
  388. numbers += quickpick(rules) + "|";
  389. }
  390. }
  391. }
  392.  
  393. break;
  394. case 'group':
  395. groupnodraws = draws;
  396. groupnoshares = lines;
  397. break;
  398. case 'raffle':
  399. isRaffle = true;
  400. LottoYardService.getRaffleTicket(productId).then(
  401. angular.bind(this, function (resp) {
  402. console.log(resp);
  403.  
  404. //if response is array else throw error
  405. if (!Array.isArray(resp)) {
  406. throw ("OLA: raffle response is not array!: error:" + resp);
  407. }
  408. var ticket = resp[0];
  409. numbers = ticket.Number + "-" + ticket.Seat + "-" + ticket.Ticket;
  410. ticketsNumbers = [ticket.Id];
  411.  
  412. var productExpire = [];
  413. var obj = {};
  414. var navidadExpiration = new Date();
  415. navidadExpiration.setMinutes(navidadExpiration.getMinutes() + RaffleExpiresInMin);
  416. obj.id = ticket.Id;
  417. obj.exp = navidadExpiration;
  418. productExpire.push(obj);
  419.  
  420. nooflines = shares;
  421.  
  422. var newItem = new ngCartItem(0, discount, groupComboBoxSelectionIndex, groupSettingsIndex, groupdiscount, groupnodraws, groupnoshares, grouporiginalprice,
  423. grouptotal, lotteryType, noofdraws, nooflines, numbers, originalprice, personalComboBoxSelectionIndex, personalSettingsIndex, selectedTab, totalCost, productName,
  424. rules.SelectNumbers, rules.MinSelectNumber, rules.MaxSelectNumbers, rules.ExtraNumbers, rules.MaxExtraNumbers, rules.MinExtraNumber, productRules.MinLines, productRules.MaxLines,
  425. rules.DrawsPerWeek, noofdraws, isFastProcessing, isSubscription, isQuickPick, ticketsNumbers, productType, productExpire, productIdSpecial, quantity, guid, isRaffle, counterGuid);
  426.  
  427. this.$cart.items.push(newItem);
  428.  
  429. $rootScope.$broadcast('ngCart:itemAdded', newItem);
  430.  
  431. $rootScope.$broadcast('ngCart:change', {});
  432.  
  433. }));
  434. return;
  435. case "product":
  436. switch (productType) {
  437. case 4:
  438. quanity = 1;
  439. noofdraws = draws;
  440. nooflines = 1;
  441. numbers = linesChecker(selectedNumbers);
  442. break;
  443.  
  444. case 14:
  445. quanity = 1;
  446. noofdraws = draws;
  447.  
  448. break;
  449.  
  450. default:
  451. }
  452.  
  453. break;
  454. default:
  455. }
  456.  
  457. var newItem = new ngCartItem(0, discount, groupComboBoxSelectionIndex, groupSettingsIndex, groupdiscount, groupnodraws, groupnoshares, grouporiginalprice,
  458. grouptotal, lotteryType, noofdraws, nooflines, numbers, originalprice, personalComboBoxSelectionIndex, personalSettingsIndex, selectedTab, totalCost, productName,
  459. rules.SelectNumbers, rules.MinSelectNumber, rules.MaxSelectNumbers, rules.ExtraNumbers, rules.MaxExtraNumbers, rules.MinExtraNumber, rules.MinLines, rules.MaxLines,
  460. rules.DrawsPerWeek, noofdraws, isFastProcessing, isSubscription, isQuickPick, ticketsNumbers, productType, productExpire, productIdSpecial, quantity, guid, isRaffle, counterGuid);
  461.  
  462. this.$cart.items.push(newItem);
  463.  
  464. $rootScope.$broadcast('ngCart:itemAdded', newItem);
  465.  
  466. $rootScope.$broadcast('ngCart:change', {});
  467. }
  468.  
  469. function quickpick(rules) {
  470. // debugger;
  471. var generatedNumbers = [];
  472. var generatedExtraNumbers = [];
  473. var line = "";
  474.  
  475. var maxSelectExtraNumbers = rules.MaxExtraNumbers; // kolko extra number to generate
  476.  
  477. var startNumber = rules.MinSelectNumber; //otkolko da startirame chislata
  478. var endNumber = rules.SelectNumbers;
  479.  
  480. var maxSelectNumbers = rules.MaxSelectNumbers; //kolko chisla da se generirat
  481.  
  482. var startExtraNumber = rules.MinExtraNumber;
  483. var endExtraNumbers = rules.ExtraNumbers;
  484.  
  485. while (generatedNumbers.length < maxSelectNumbers) {
  486. var number = getRandomInt(startNumber, endNumber);
  487. if (generatedNumbers.indexOf(number) === -1) {
  488. generatedNumbers.push(number);
  489. console.log(number);
  490. }
  491. }
  492. line += generatedNumbers.join(',');
  493.  
  494. if (maxSelectExtraNumbers > 0) {
  495. while (generatedExtraNumbers.length < maxSelectExtraNumbers) {
  496. var number = getRandomInt(startExtraNumber, endExtraNumbers);
  497. if (generatedExtraNumbers.indexOf(number) === -1) {
  498. generatedExtraNumbers.push(number);
  499. console.log(number);
  500. }
  501. }
  502.  
  503. line += '#' + generatedExtraNumbers.join(',');
  504. }
  505. return line;
  506.  
  507. function getRandomInt(min, max) {
  508. return Math.floor(Math.random() * (max - min + 1)) + min;
  509. };
  510. };
  511.  
  512. function isNumeric(n) {
  513. return !isNaN(parseFloat(n)) && isFinite(n);
  514. };
  515.  
  516. function linesChecker(numbers) {
  517. var numberSeperator = ',';
  518. var linesSeperator = '|';
  519. var specialNumberSeperator = "#";
  520.  
  521. var arrLength = numbers.length;
  522.  
  523. var numbersSanitized = "";
  524. var currentNumbersInline = 1;
  525.  
  526. for (var i = 0; i < arrLength; i++) {
  527. var currentElement = numbers[i];
  528. var nextElement = numbers[i + 1];
  529.  
  530. if (i === 0) {
  531. if (isNumeric(currentElement)) {
  532. numbersSanitized += currentElement;
  533. currentNumbersInline++;
  534. continue;
  535. } else {
  536. continue;
  537. }
  538. }
  539.  
  540. if (isNumeric(currentElement)) {
  541. numbersSanitized += currentElement;
  542. currentNumbersInline++;
  543. continue;
  544. }
  545.  
  546. if (currentElement === numberSeperator || currentElement === linesSeperator || currentElement === specialNumberSeperator) {
  547. if (typeof nextElement !== 'undefined') {
  548. if (isNumeric(nextElement)) {
  549. numbersSanitized += currentElement;
  550. continue;
  551. }
  552. }
  553. }
  554. }
  555.  
  556. function isNumeric(n) {
  557. return !isNaN(parseFloat(n)) && isFinite(n);
  558. };
  559. console.log(numbersSanitized);
  560. return numbersSanitized;
  561.  
  562. }
  563.  
  564. this.getItemById = function (itemId) {
  565. var items = this.getCart().items;
  566. var build = false;
  567.  
  568. angular.forEach(items, function (item) {
  569. if (item.getId() === itemId) {
  570. build = item;
  571. }
  572. });
  573. return build;
  574. };
  575.  
  576. this.setShipping = function (shipping) {
  577. this.$cart.shipping = shipping;
  578. return this.getShipping();
  579. };
  580.  
  581. this.getShipping = function () {
  582. if (this.getCart().items.length === 0) return 0;
  583. return this.getCart().shipping;
  584. };
  585.  
  586. this.setTaxRate = function (taxRate) {
  587. this.$cart.taxRate = +parseFloat(taxRate).toFixed(2);
  588. return this.getTaxRate();
  589. };
  590.  
  591. this.getTaxRate = function () {
  592. return this.getCart().taxRate;
  593. };
  594.  
  595. this.getTax = function () {
  596. return +parseFloat(((this.getSubTotal() / 100) * this.getCart().taxRate)).toFixed(2);
  597. };
  598.  
  599. this.setCart = function (cart) {
  600. this.$cart = cart;
  601. return this.getCart();
  602. };
  603.  
  604. this.getCart = function () {
  605. return this.$cart;
  606. };
  607.  
  608. this.getItems = function () {
  609. return this.getCart().items;
  610. };
  611.  
  612. this.setItems = function (items) {
  613. this.$cart.items = items;
  614. };
  615.  
  616. this.getTopNItems = function (n) {
  617. return this.getCart().items.slice(0, n);
  618. };
  619.  
  620. this.getTotalItems = function () {
  621. var count = 0;
  622. var items = this.getItems();
  623. angular.forEach(items, function (item) {
  624. count += item.getQuantity();
  625. });
  626. return count;
  627. };
  628.  
  629. this.getTotalUniqueItems = function () {
  630. return this.getCart().items.length;
  631. };
  632.  
  633. this.getSubTotal = function () {
  634. var total = 0;
  635. angular.forEach(this.getCart().items, function (item) {
  636. total += item.getTotal();
  637. });
  638. return +parseFloat(total).toFixed(2);
  639. };
  640.  
  641. this.totalCost = function () {
  642. var fastProcessingTax = 0;
  643. angular.forEach(this.getCart().items, function (item) {
  644. if (item._isFastProcessing) {
  645. fastProcessingTax += 0.79;
  646. }
  647. });
  648.  
  649. return +parseFloat(this.getSubTotal() + this.getShipping() + this.getTax() + fastProcessingTax).toFixed(2);
  650. };
  651.  
  652. this.setAmountToPay = function (price) {
  653. this.$cart.amountToPay = price;
  654. };
  655.  
  656. this.getAmountToPay = function () {
  657. if (this.$cart.amountToPay >= 0) {
  658. return this.$cart.amountToPay;
  659. }
  660. return this.totalCost();
  661. };
  662.  
  663. this.removeItem = function (index) {
  664. this.$cart.items.splice(index, 1);
  665. $rootScope.$broadcast('ngCart:itemRemoved', {});
  666. $rootScope.$broadcast('ngCart:change', {});
  667.  
  668. };
  669.  
  670. this.removeItemById = function (id) {
  671. var cart = this.getCart();
  672. angular.forEach(cart.items, function (item, index) {
  673. if (item.getId() === id) {
  674. cart.items.splice(index, 1);
  675. }
  676. });
  677. this.setCart(cart);
  678. $rootScope.$broadcast('ngCart:itemRemoved', {});
  679. $rootScope.$broadcast('ngCart:change', {});
  680. };
  681.  
  682. this.empty = function () {
  683. $rootScope.$broadcast('ngCart:change', {});
  684. this.$cart.items = [];
  685. store.emptyCart();
  686. };
  687.  
  688. this.isEmpty = function () {
  689. return (this.$cart.items.length > 0 ? false : true);
  690. };
  691.  
  692. this.setIframePaymentMethods = function (iframePaymentMethods) {
  693. this.$cart.iframePaymentMethods = iframePaymentMethods;
  694. return this.getIframePaymentMethods();
  695. };
  696.  
  697. this.getIframePaymentMethods = function () {
  698. return this.$cart.iframePaymentMethods;
  699. };
  700.  
  701. this.setPaymentMethodId = function (paymentMethodId) {
  702. this.$cart.paymentMethodId = paymentMethodId;
  703. return this.getPaymentMethodId();
  704. };
  705.  
  706. this.getPhoneOrEmail = function () {
  707. return this.$cart.phoneOrEmail;
  708. };
  709.  
  710. this.setPhoneOrEmail = function (phoneOrEmail) {
  711. this.$cart.phoneOrEmail = phoneOrEmail;
  712. };
  713.  
  714. this.getPaymentMethodId = function () {
  715. return this.$cart.paymentMethodId;
  716. };
  717.  
  718. this.setProcessor = function (processor) {
  719. this.$cart.processor = processor;
  720. };
  721.  
  722. this.getProcessor = function () {
  723. return this.$cart.processor;
  724. };
  725.  
  726. this.setReedemCode = function (reedem) {
  727. //debugger
  728. this.$cart.reedemCode = reedem;
  729. return this.getReedemCode();
  730. };
  731.  
  732. this.getReedemCode = function () {
  733. return this.$cart.reedemCode;
  734. };
  735.  
  736. this.setReedemBonusAmount = function (reedemBonusAmount) {
  737. this.$cart.reedemBonusAmount = reedemBonusAmount;
  738. return this.getReedemBonusAmount();
  739. };
  740.  
  741. this.getReedemBonusAmount = function () {
  742. if (this.$cart.reedemBonusAmount < 0) {
  743. return 0;
  744. } else {
  745. return this.$cart.reedemBonusAmount;
  746. }
  747.  
  748. };
  749.  
  750. this.setAffiliateCode = function (aff) {
  751. this.$cart.affiliateCode = aff;
  752. return this.getAffiliateCode();
  753. };
  754.  
  755. this.getAffiliateCode = function () {
  756. return this.$cart.affiliateCode;
  757. };
  758.  
  759. this.setOlapAffiliateCode = function (aff) {
  760. this.$cart.olapAffiliateCode = aff;
  761. return this.getOlapAffiliateCode();
  762. };
  763.  
  764. this.getOlapAffiliateCode = function () {
  765. return this.$cart.olapAffiliateCode;
  766. };
  767.  
  768. this.setIsFastProcessing = function (isFastProcessing) {
  769. this.$cart.isFastProcessing = isFastProcessing;
  770. return this.getIsFastProcessing();
  771. };
  772.  
  773. this.getIsFastProcessing = function () {
  774. return this.$cart.isFastProcessing;
  775. };
  776.  
  777. this.setFastProcessingTax = function (fastProcessingTax) {
  778. this.$cart.fastProcessingTax = fastProcessingTax;
  779. return this.getFastProcessingTax();
  780. };
  781.  
  782. this.getFastProcessingTax = function () {
  783. return this.$cart.fastProcessingTax;
  784. };
  785.  
  786. this.setCurrency = function (currency) {
  787. this.$cart.currency = currency;
  788. return this.getCurrency();
  789. };
  790.  
  791. this.getCurrency = function () {
  792. return this.$cart.currency;
  793. };
  794.  
  795. this.getBonusAmountToUse = function () {
  796. return this.$cart.bonusAmountToUse;
  797. }
  798.  
  799. this.setBonusAmountToUse = function (bonusAmountToUse) {
  800. this.$cart.bonusAmountToUse = bonusAmountToUse;
  801. }
  802.  
  803. this.getUseBonusmoney = function () {
  804. return this.$cart.useBonusmoney;
  805. }
  806.  
  807. this.setUseBonusmoney = function (isUsingBonusmoney) {
  808. this.$cart.useBonusmoney = isUsingBonusmoney;
  809. }
  810.  
  811.  
  812. //this.getEvenLinesOnlyMessage = function () {
  813. // return this.$cart.evenLinesOnlyMessage;
  814. //}
  815.  
  816. //this.setEvenLinesOnlyMessage = function (evenLinesOnlyMessage) {
  817. // this.$cart.evenLinesOnlyMessage = evenLinesOnlyMessage;
  818. //}
  819.  
  820. this.toObject = function () {
  821. if (this.getItems().length === 0) return false;
  822. console.log(items);
  823. //var items = [];
  824. //angular.forEach(this.getItems(), function (item) {
  825. // items.push(item.toObject());
  826. //});
  827.  
  828. //return {
  829. // shipping: this.getShipping(),
  830. // tax: this.getTax(),
  831. // taxRate: this.getTaxRate(),
  832. // subTotal: this.getSubTotal(),_evenLinesOnly
  833. // totalCost: this.totalCost(),
  834. // items: items
  835. //}
  836. return items;
  837. };
  838.  
  839. this.$restore = function (storedCart) {
  840. // debugger
  841. var _self = this;
  842. _self.init();
  843. _self.$cart.shipping = storedCart.shipping;
  844. _self.$cart.tax = storedCart.tax;
  845. _self.$cart.iframePaymentMethods = storedCart.iframePaymentMethods;
  846. _self.$cart.paymentMethodId = storedCart.paymentMethodId;
  847. _self.$cart.processor = storedCart.processor;
  848. _self.$cart.fastProcessingTax = storedCart.fastProcessingTax;
  849. _self.$cart.amountToPay = storedCart.amountToPay;
  850. _self.$cart.phoneOrEmail = storedCart.phoneOrEmail;
  851. _self.$cart.reedemCode = storedCart.reedemCode;
  852. _self.$cart.isFastProcessing = storedCart.isFastProcessing;
  853. _self.$cart.affiliateCode = storedCart.affiliateCode;
  854. _self.$cart.reedemBonusAmount = storedCart.reedemBonusAmount;
  855. _self.$cart.olapAffiliateCode = storedCart.olapAffiliateCode;
  856. _self.$cart.currency = storedCart.currency;
  857. _self.$cart.bonusAmountToUse = storedCart.bonusAmountToUse;
  858. _self.$cart.useBonusmoney = storedCart.useBonusmoney;
  859. _self.$cart.evenLinesOnlyMessage = storedCart.evenLinesOnlyMessage;
  860.  
  861. angular.forEach(storedCart.items, function (item) {
  862. _self.$cart.items.push(new ngCartItem(item._id, item._discount, item._groupComboBoxSelectionIndex, item._groupSettingsIndex, item._groupdiscount, item._groupnodraws, item._groupnoshares, item._grouporiginalprice,
  863. item._grouptotal, item._lotteryType, item._noofdraws, item._nooflines, item._numbers, item._originalprice, item._personalComboBoxSelectionIndex, item._personalSettingsIndex, item._selectedTab, item._totalCost, item._lotteryName,
  864. item._selectNumbers, item._minselectNumbers, item._maxselectNumbers, item._extraNumbers, item._maxExtraNumbers, item._minExtraNumber, item._minLines, item._maxLines, item._drawsPerWeek, item._productsDrawOptions, item._isFastProcessing,
  865. item._isSubscription, item._isQuickPick, item._ticketsNumbersId, item._productType, item._productExpire, item._productIdSpecial, item._quantity, item._guid, item._isRaffle, item._counterGuid, item._evenLinesOnly));
  866. });
  867. this.$save();
  868. };
  869.  
  870. this.$save = function () {
  871. var r = this.getCart();
  872. var test = store.set('cart', JSON.stringify(this.getCart()));
  873.  
  874. return store.set('cart', JSON.stringify(this.getCart()));
  875. }
  876.  
  877. this.isContainOlapProduct = function () {
  878. var cartLength = this.$cart.items.length;
  879.  
  880. for (var i = 0, len = cartLength; i < len; i++) {
  881. if (this.$cart.items[i].getProductIdSpecial() === 999) {
  882. return true;
  883. }
  884. }
  885. return false;
  886. };
  887. }
  888. ])
  889. .factory('ngCartItem', [
  890. '$rootScope', '$log', '$timeout', function ($rootScope, $log) {
  891.  
  892. var item = function (id, discount, groupComboBoxSelectionIndex, groupSettingsIndex, groupdiscount, groupnodraws, groupnoshares, grouporiginalprice,
  893. grouptotal, lotteryType, noofdraws, nooflines, numbers, originalprice, personalComboBoxSelectionIndex, personalSettingsIndex, selectedTab, totalCost, lotteryname,
  894. selectNumbers, minSelectNumber, maxSelectNumbers, extraNumbers, maxExtraNumbers, minExtraNumber, minLines, maxLines, drawsPerWeek, productsDrawOptions, isFastProcessing,
  895. isSubscription, isQuickPick, ticketsNumbers, productType, productExpire, productIdSpecial, quantity, guid, isRaffle, counterGuid, evenLinesOnly) {
  896. this.setId(id);
  897. this.setDiscount(discount);
  898. this.setGroupComboBoxSelectionIndex(groupComboBoxSelectionIndex);
  899. this.setGroupSettingsIndex(groupSettingsIndex);
  900. this.setGroupdiscount(groupdiscount);
  901. this.setGroupnodraws(groupnodraws);
  902. this.setGroupnoshares(groupnoshares);
  903. this.setGrouporiginalprice(grouporiginalprice);
  904. this.setGroupTotal(grouptotal);
  905. this.setLotteryType(lotteryType);
  906. this.setNumberOfDraws(noofdraws);
  907. this.setNumberOfLines(nooflines);
  908. this.setNumbers(numbers);
  909. this.setOriginalPrice(originalprice);
  910. this.setPersonalComboBoxSelectionIndex(personalComboBoxSelectionIndex);
  911. this.setPersonalSettingsIndex(personalSettingsIndex);
  912. this.setSelectedTab(selectedTab);
  913. this.setTotalCost(totalCost);
  914. this.setTotalDiscount();
  915. this.setNumbersSantized(numbers);
  916. this.setLotteryType(lotteryType);
  917. this.setLotteryName(lotteryname);
  918. this.setProductType(productType);
  919. this.setProductExpire(productExpire);
  920.  
  921. //lottery rules
  922. this.setSelectNumbers(selectNumbers);
  923. this.setMinSelectNumbers(minSelectNumber);
  924. this.setMaxSelectNumbers(maxSelectNumbers);
  925. this.setExtraNumbers(extraNumbers);
  926. this.setMaxExtraNumbers(maxExtraNumbers);
  927. this.setMinExtraNumber(minExtraNumber);
  928. this.setMinLines(minLines);
  929. this.setMaxLines(maxLines);
  930. this.setDrawsPerWeek(drawsPerWeek);
  931. this.setProductsDrawOptions(productsDrawOptions);
  932. this.setIsFastProcessing(isFastProcessing);
  933. this.setIsSubscription(isSubscription);
  934. this.setIsQuickPick(isQuickPick);
  935. this.setTicketsNumbersId(ticketsNumbers);
  936.  
  937. //counterGuid
  938. this.setCounterGuid(counterGuid);
  939. //isRaffle
  940. this.setIsRaffle(isRaffle);
  941. this.setProductIdSpecial(productIdSpecial);
  942. this.setGuid(guid);
  943.  
  944. if (!evenLinesOnly && lotteryType == 14) {
  945. evenLinesOnly = true;
  946. }
  947.  
  948. this.setEvenLinesOnly(evenLinesOnly)
  949.  
  950. //this.setPrice(price);
  951. //this.setQuantity(quantity);
  952. this.setQuantity(quantity);
  953.  
  954.  
  955. };
  956.  
  957. item.prototype.setId = function (id) {
  958. if (id) this._id = id;
  959. else {
  960. this._id = generateUid();
  961. $log.info('An ID is auto generated:' + this._id);
  962. }
  963. };
  964.  
  965. item.prototype.getId = function () {
  966. return this._id;
  967. };
  968.  
  969. item.prototype.setDiscount = function (discount) {
  970. this._discount = (discount);
  971. };
  972.  
  973. item.prototype.getDiscount = function () {
  974. if (this._productType === 1) {
  975. return this._discount.toFixed(3);
  976. } else {
  977. return this._groupdiscount.toFixed(2);
  978. }
  979. };
  980.  
  981. item.prototype.setGroupComboBoxSelectionIndex = function (groupComboBoxSelectionIndex) {
  982. this._groupComboBoxSelectionIndex = (groupComboBoxSelectionIndex);
  983. };
  984.  
  985. item.prototype.getGroupComboBoxSelectionIndex = function () {
  986. return this._groupComboBoxSelectionIndex;
  987. };
  988.  
  989. item.prototype.setGroupSettingsIndex = function (groupSettingsIndex) {
  990. this._groupSettingsIndex = (groupSettingsIndex);
  991. };
  992.  
  993. item.prototype.getGroupSettingsIndex = function () {
  994. return this._groupSettingsIndex;
  995. };
  996.  
  997. item.prototype.setGroupdiscount = function (groupdiscount) {
  998. //todo check is group then should not be 0
  999. this._groupdiscount = (groupdiscount);
  1000. };
  1001.  
  1002. item.prototype.getGroupdiscount = function () {
  1003. return this._groupdiscount;
  1004. };
  1005.  
  1006. item.prototype.setGroupnodraws = function (groupnodraws) {
  1007. this._groupnodraws = parseInt(groupnodraws);
  1008. };
  1009.  
  1010. item.prototype.getGroupnodraws = function () {
  1011. return this._groupnodraws;
  1012. };
  1013.  
  1014. item.prototype.setGroupnoshares = function (groupnoshares) {
  1015. this._groupnoshares = parseInt(groupnoshares);
  1016. };
  1017.  
  1018. item.prototype.getGroupnoshares = function () {
  1019. return this._groupnoshares;
  1020. };
  1021.  
  1022. item.prototype.setGrouporiginalprice = function (grouporiginalprice) {
  1023. this._grouporiginalprice = (grouporiginalprice);
  1024. };
  1025.  
  1026. item.prototype.getGrouporiginalprice = function () {
  1027. return this._grouporiginalprice;
  1028. };
  1029.  
  1030. item.prototype.setGroupTotal = function (grouptotal) {
  1031. this._grouptotal = (grouptotal);
  1032. };
  1033.  
  1034. item.prototype.getGroupTotal = function () {
  1035. return this._grouptotal;
  1036. };
  1037.  
  1038. item.prototype.setLotteryType = function (lotteryType) {
  1039. if (lotteryType) {
  1040. if (lotteryType <= 0) {
  1041. $log.error('A lotteryType must be over 0');
  1042. } else {
  1043. this._lotteryType = (lotteryType);
  1044. }
  1045. } else {
  1046. $log.error('A lotteryType must be provided');
  1047. }
  1048. };
  1049.  
  1050. item.prototype.getLotteryType = function () {
  1051. return this._lotteryType;
  1052. };
  1053.  
  1054. item.prototype.setLotteryName = function (lotteryname) {
  1055. if (lotteryname === 'NavidadPersonal') {
  1056. this._lotteryName = 'Navidad';
  1057. } else {
  1058. this._lotteryName = lotteryname;
  1059. }
  1060.  
  1061. };
  1062.  
  1063. item.prototype.getLotteryName = function () {
  1064. return this._lotteryName;
  1065. };
  1066.  
  1067. item.prototype.setNumberOfDraws = function (noofdraws) {
  1068. this._noofdraws = (noofdraws);
  1069. };
  1070.  
  1071. item.prototype.getNumberOfDraws = function () {
  1072. if (this._selectedTab === 'groupselection' || this._productType === 3) {
  1073. return this._groupnodraws;
  1074. }
  1075. return this._noofdraws;
  1076. };
  1077.  
  1078. item.prototype.getNumberOfLinesOrShares = function () {
  1079. if (this._productType !== 1) {
  1080. return this._groupnoshares;
  1081. }
  1082. return this._nooflines;
  1083. };
  1084.  
  1085. item.prototype.setNumberOfLines = function (nooflines) {
  1086. this._nooflines = (nooflines);
  1087. };
  1088.  
  1089. item.prototype.getNumberOfLines = function () {
  1090. return this._nooflines;
  1091. };
  1092.  
  1093. item.prototype.setNumbers = function (numbers) {
  1094. // debugger;
  1095. var newNumbers;
  1096. var currentLines;
  1097. if (typeof (numbers) !== 'undefined' && numbers !== "") {
  1098. newNumbers = "";
  1099. currentLines = 1;
  1100. for (var i = 0, len = numbers.length; i < len; i++) {
  1101. var pattern = '|';
  1102. var currentChar = numbers[i];
  1103. var nextChar = numbers[i + 1];
  1104.  
  1105. if (currentChar !== pattern) {
  1106. newNumbers += currentChar;
  1107. } else {
  1108.  
  1109. if (nextChar === pattern || typeof (nextChar) === 'undefined') {
  1110. continue;
  1111. }
  1112.  
  1113. currentLines++;
  1114. newNumbers += pattern;
  1115. }
  1116. }
  1117.  
  1118. if (currentLines !== this._nooflines) {
  1119. console.warn('mismatching lines in numebrs');
  1120. }
  1121. }
  1122.  
  1123. this._numbers = newNumbers;
  1124. };
  1125.  
  1126. item.prototype.getNumbers = function () {
  1127. return this._numbers;
  1128. };
  1129.  
  1130. item.prototype.setNumbersSantized = function (numbers) {
  1131. //debugger;
  1132. if (typeof (numbers) !== 'undefined') {
  1133. if (numbers.indexOf(',') !== -1) {
  1134. if (numbers.length > 0) {
  1135. var lines = numbers.split('|');
  1136. lines = lines.filter(function (e) { return e.replace(/(\r\n|\n|\r)/gm, "") });
  1137. this._numbersSantized = lines;
  1138. } else {
  1139. this._numbersSantized = [];
  1140. }
  1141. } else {
  1142. this._numbersSantized = [];
  1143. this._numbersSantized.push(numbers);
  1144. }
  1145. } else {
  1146. this._numbersSantized = [];
  1147. this._numbersSantized.push(numbers);
  1148. }
  1149. };
  1150.  
  1151. item.prototype.getNumbersSantized = function () {
  1152. return this._numbersSantized;
  1153. };
  1154.  
  1155. item.prototype.getLinesNumbers = function (line) {
  1156. // debugger;
  1157. if (this._lotteryType === 13) {
  1158. return line;
  1159. }
  1160. var lines = this._numbersSantized[line];
  1161. var numberslines = lines.split(',');
  1162.  
  1163. if (lines.indexOf('#') !== -1) {
  1164. numberslines = lines.split('#')[0].split(',');
  1165. }
  1166. return numberslines;
  1167.  
  1168.  
  1169. };
  1170.  
  1171. item.prototype.getLinesSpecialNumbers = function (line) {
  1172. //todo check if okay
  1173. var lines = this._numbersSantized[line];
  1174.  
  1175. if (lines.indexOf('#') !== -1) {
  1176. return lines.split('#')[1].split(',');
  1177. }
  1178. return 0;
  1179. };
  1180.  
  1181. item.prototype.setOriginalPrice = function (originalprice) {
  1182. this._originalprice = (originalprice);
  1183. };
  1184.  
  1185. item.prototype.getOriginalPrice = function () {
  1186. return this._originalprice;
  1187. };
  1188.  
  1189. item.prototype.setPersonalComboBoxSelectionIndex = function (personalComboBoxSelectionIndex) {
  1190.  
  1191. this._personalComboBoxSelectionIndex = (personalComboBoxSelectionIndex);
  1192.  
  1193. };
  1194.  
  1195. item.prototype.getPersonalComboBoxSelectionIndex = function () {
  1196. return this._personalComboBoxSelectionIndex;
  1197. };
  1198.  
  1199. item.prototype.setPersonalSettingsIndex = function (personalSettingsIndex) {
  1200.  
  1201. this._personalSettingsIndex = personalSettingsIndex;
  1202.  
  1203. };
  1204.  
  1205. item.prototype.getPersonalSettingsIndex = function () {
  1206. return this._personalSettingsIndex;
  1207. };
  1208.  
  1209. item.prototype.setSelectedTab = function (selectedTab) {
  1210. this._selectedTab = (selectedTab);
  1211. }
  1212.  
  1213. item.prototype.getSelectedTab = function () {
  1214. return this._selectedTab;
  1215. };
  1216.  
  1217. item.prototype.setTotalCost = function (totalCost) {
  1218. this._totalCost = parseFloat(totalCost);
  1219. };
  1220.  
  1221. item.prototype.getTotalCost = function () {
  1222. return this._totalCost;
  1223. };
  1224.  
  1225. item.prototype.setTotalDiscount = function (dis) {
  1226. //debugger
  1227. if (typeof (dis) === 'undefined') {
  1228. if (this._groupdiscount > 0) {
  1229. var price = this._totalCost + ((this._totalCost / (1 - this._groupdiscount)) * this._groupdiscount);
  1230. this._totalDiscount = this._groupdiscount * price;
  1231. } else {
  1232. var price = this._totalCost;
  1233. this._totalDiscount = this._groupdiscount * price;
  1234. }
  1235. } else {
  1236. this._totalDiscount = dis;
  1237. }
  1238. };
  1239.  
  1240. item.prototype.getTotalDiscount = function () {
  1241. // debugger;
  1242. if (this._productType === 1) {
  1243. return ((this._nooflines * this._originalprice * parseInt(this._noofdraws)) * this._discount).toFixed(2);
  1244. } else {
  1245. //debugger;
  1246. return this._totalDiscount;
  1247. }
  1248. };
  1249.  
  1250. item.prototype.removeLastLine = function () {
  1251. var lastLine = this._numbers.lastIndexOf('|');
  1252.  
  1253.  
  1254. var newNumbers = this._numbers.substring(0, lastLine);
  1255. this._numbers = newNumbers;
  1256.  
  1257. this.setNumbersSantized(newNumbers);
  1258.  
  1259. $rootScope.$broadcast('ngCart:change', {});
  1260. };
  1261.  
  1262. item.prototype.updateSantizedLine = function (numbers, line) {
  1263. if (this._numbersSantized.length < line) {
  1264. console.log('new line');
  1265. this._numbers += '|' + numbers;
  1266. this._numbersSantized.push(numbers);
  1267. this._nooflines++;
  1268. } else {
  1269. this._numbersSantized[line - 1] = numbers;
  1270. var splited = this._numbers.split('|');
  1271. splited[line - 1] = numbers;
  1272. this._numbers = splited.join('|');
  1273. }
  1274.  
  1275. $rootScope.$broadcast('ngCart:change', {});
  1276. }
  1277.  
  1278. item.prototype.setProductType = function (productType) {
  1279. this._productType = productType;
  1280. };
  1281.  
  1282. item.prototype.getProductType = function () {
  1283. return this._productType;
  1284. };
  1285.  
  1286. item.prototype.getLineOrShareText = function () {
  1287. if (this._productType === 1) {
  1288. return "Line";
  1289. }
  1290. return "Share";
  1291. }
  1292.  
  1293. //lottery rules properties
  1294. item.prototype.getSelectNumbers = function () {
  1295. return this._selectNumbers;
  1296. };
  1297.  
  1298. item.prototype.setSelectNumbers = function (selectNumbers) {
  1299. this._selectNumbers = selectNumbers;
  1300. };
  1301.  
  1302. item.prototype.getMinSelectNumbers = function () {
  1303. return this._minselectNumbers;
  1304. };
  1305.  
  1306. item.prototype.setMinSelectNumbers = function (minselectNumbers) {
  1307. this._minselectNumbers = minselectNumbers;
  1308. };
  1309.  
  1310. item.prototype.getMaxSelectNumbers = function () {
  1311. return this._maxselectNumbers;
  1312. };
  1313.  
  1314. item.prototype.setMaxSelectNumbers = function (maxselectNumbers) {
  1315. this._maxselectNumbers = maxselectNumbers;
  1316. };
  1317.  
  1318. item.prototype.getExtraNumbers = function () {
  1319. return this._extraNumbers;
  1320. };
  1321.  
  1322. item.prototype.setExtraNumbers = function (extraNumbers) {
  1323. this._extraNumbers = extraNumbers;
  1324. };
  1325.  
  1326. item.prototype.getMaxExtraNumbers = function () {
  1327. return this._maxExtraNumbers;
  1328. };
  1329.  
  1330. item.prototype.setMaxExtraNumbers = function (maxExtraNumbers) {
  1331. this._maxExtraNumbers = maxExtraNumbers;
  1332. };
  1333.  
  1334. item.prototype.getMinExtraNumber = function () {
  1335. return this._minExtraNumber;
  1336. };
  1337.  
  1338. item.prototype.setMinExtraNumber = function (minExtraNumber) {
  1339. this._minExtraNumber = minExtraNumber;
  1340. };
  1341.  
  1342. item.prototype.getMinLines = function () {
  1343.  
  1344. return this._minLines;
  1345. };
  1346.  
  1347. item.prototype.setMinLines = function (minLines) {
  1348. this._minLines = minLines;
  1349. };
  1350.  
  1351. item.prototype.getMaxLines = function () {
  1352. return this._maxLines;
  1353. };
  1354.  
  1355. item.prototype.setMaxLines = function (maxLines) {
  1356. this._maxLines = maxLines;
  1357. };
  1358.  
  1359. item.prototype.getDrawsPerWeek = function () {
  1360. return this._drawsPerWeek;
  1361. };
  1362.  
  1363. item.prototype.setDrawsPerWeek = function (drawsPerWeek) {
  1364. this._drawsPerWeek = drawsPerWeek;
  1365. };
  1366.  
  1367. item.prototype.setProductsDrawOptions = function (productsDrawOptions) {
  1368. this._productsDrawOptions = productsDrawOptions;
  1369. };
  1370.  
  1371. item.prototype.getProductsDrawOptions = function () {
  1372. //check what type is single or group
  1373. var toReturn = [];
  1374. var self = this;
  1375. if (this._productType === 1) {
  1376.  
  1377. angular.forEach(this._productsDrawOptions, function (value, key) {
  1378. if (value.ProductId === 1 && value.IsSubscription === self._isSubscription) {
  1379. toReturn = value.MultiDrawOptions;
  1380. }
  1381. });
  1382.  
  1383. } else if (this._productType === 3 || (this._selectedTab === "product" && this._productType === 3)) {
  1384. angular.forEach(this._productsDrawOptions, function (value, key) {
  1385. if (value.ProductId === 3 && value.IsSubscription === self._isSubscription) {
  1386. toReturn = value.MultiDrawOptions;
  1387. }
  1388. });
  1389. } else if (this._selectedTab === "product") {
  1390. //debugger;
  1391.  
  1392. var refactoredArray = [];
  1393. angular.forEach(this._productsDrawOptions, function (value, key) {
  1394. refactoredArray.push({
  1395. Discount: 0,
  1396. NumberOfDraws: value
  1397. });
  1398. });
  1399.  
  1400. return refactoredArray;
  1401. }
  1402.  
  1403. return toReturn;
  1404. };
  1405.  
  1406. item.prototype.getProductsSubscriptionOptions = function () {
  1407. //check what type is single or group
  1408. var toReturn = [];
  1409.  
  1410. if (this._productType === 1) {
  1411.  
  1412. angular.forEach(this._productsDrawOptions, function (value, key) {
  1413. if (value.ProductId === 1 && value.IsSubscription) {
  1414. toReturn = value.MultiDrawOptions;
  1415. }
  1416. });
  1417.  
  1418. } else {
  1419. angular.forEach(this._productsDrawOptions, function (value, key) {
  1420. if (value.ProductId === 3 && value.IsSubscription) {
  1421. toReturn = value.MultiDrawOptions;
  1422. }
  1423. });
  1424. }
  1425.  
  1426. return toReturn;
  1427. };
  1428.  
  1429. item.prototype.setProductExpire = function (productExpire) {
  1430. // console.log(productExpire);
  1431. this._productExpire = productExpire;
  1432. };
  1433.  
  1434. item.prototype.getProductExpire = function () {
  1435. if (typeof this._productExpire !== "undefined" && this._productExpire !== null && this._productExpire.length > 0) {
  1436. var countDown = this._productExpire[0].exp;
  1437. var future = new Date(countDown);
  1438. var diff = Math.floor((future.getTime() - new Date().getTime()) / 1000);
  1439.  
  1440. return diff;
  1441. } else {
  1442. return 0;
  1443. }
  1444.  
  1445. };
  1446.  
  1447. item.prototype.getNavidadTickets = function (counter) {
  1448. var arr = this._numbers.split('|')
  1449. if (typeof counter === 'undefined') {
  1450. return arr;
  1451. } else {
  1452. return arr.slice(0, counter);
  1453. }
  1454. };
  1455.  
  1456. item.prototype.getNavidadTicket = function (line) {
  1457. return this._numbers.split('|')[line].split("-");
  1458. };
  1459.  
  1460. item.prototype.setQuantity = function (qty) {
  1461. this._quantity = qty;
  1462. };
  1463.  
  1464. item.prototype.getQuantity = function () {
  1465. return this._quantity;
  1466. };
  1467.  
  1468. item.prototype.setTicketsNumbersId = function (ticketsNumbers) {
  1469. this._ticketsNumbersId = ticketsNumbers;
  1470. };
  1471.  
  1472. item.prototype.getTicketsNumbersId = function () {
  1473. return this._ticketsNumbersId;
  1474. };
  1475.  
  1476. item.prototype.getTotal = function () {
  1477. return +parseFloat(this.getTotalCost()).toFixed(2);
  1478. };
  1479.  
  1480. item.prototype.setIsFastProcessing = function (isFastProcessing) {
  1481. if (typeof (isFastProcessing) === 'undefined') {
  1482. isFastProcessing = false;
  1483. }
  1484. this._isFastProcessing = isFastProcessing;
  1485. };
  1486.  
  1487. item.prototype.getIsFastProcessing = function () {
  1488. return this._isFastProcessing;
  1489. };
  1490.  
  1491. item.prototype.setIsSubscription = function (isSubscription) {
  1492. if (typeof (isSubscription) === 'undefined') {
  1493. isSubscription = false;
  1494. }
  1495. this._isSubscription = isSubscription;
  1496. };
  1497.  
  1498. item.prototype.getIsSubscription = function () {
  1499. return this._isSubscription;
  1500. };
  1501.  
  1502. item.prototype.setIsQuickPick = function (isQuickPick) {
  1503. if (typeof (isQuickPick) === 'undefined') {
  1504. isQuickPick = false;
  1505. }
  1506. this._isQuickPick = isQuickPick;
  1507. };
  1508.  
  1509. item.prototype.getIsQuickPick = function () {
  1510. return this._isQuickPick;
  1511. };
  1512.  
  1513. item.prototype.setProductIdSpecial = function (productIdSpecial) {
  1514. this._productIdSpecial = productIdSpecial;
  1515. }
  1516.  
  1517. item.prototype.getProductIdSpecial = function () {
  1518. return this._productIdSpecial;
  1519. }
  1520.  
  1521. item.prototype.setIsRaffle = function (isRaffle) {
  1522. this._isRaffle = isRaffle;
  1523. }
  1524.  
  1525. item.prototype.getIsRaffle = function () {
  1526. return this._isRaffle;
  1527. };
  1528. item.prototype.setCounterGuid = function (counterGuid) {
  1529. this._counterGuid = counterGuid;
  1530. }
  1531.  
  1532. item.prototype.getCounterGuid = function () {
  1533. return this._counterGuid;
  1534. };
  1535. item.prototype.setGuid = function (guid) {
  1536. this._guid = guid;
  1537. }
  1538.  
  1539. item.prototype.getGuid = function () {
  1540. return this._guid;
  1541. }
  1542.  
  1543. item.prototype.setEvenLinesOnly = function (evenLinesOnly) {
  1544. return this._evenLinesOnly = evenLinesOnly;
  1545. }
  1546.  
  1547. item.prototype.getEvenLinesOnly = function () {
  1548. return this._evenLinesOnly;
  1549. }
  1550.  
  1551. item.prototype.toObject = function () {
  1552.  
  1553. return {
  1554. id: this.getId(),
  1555. lines: this.getNumberOfLines(),
  1556. draws: this.getNumberOfDraws(),
  1557. // name: this.getName(),
  1558. // price: this.getPrice(),
  1559. // quantity: this.getQuantity(),
  1560. // data: this.getData(),
  1561. total: this.getTotalCost()
  1562. }
  1563. };
  1564.  
  1565. function generateUid() {
  1566. return ("0000" + (Math.random() * Math.pow(36, 4) << 0).toString(36)).slice(-4);
  1567. }
  1568.  
  1569. return item;
  1570.  
  1571. }
  1572. ])
  1573. .service('store', [
  1574. '$window', 'CacheFactory', function ($window, CacheFactory) {
  1575.  
  1576. var dataCache = CacheFactory('cart', {
  1577. maxAge: 60 * 60 * 1000, // Items added to this cache expire after 60 minutes
  1578. // cacheFlushInterval: 60 * 60 * 1000, // This cache will clear itself every 60 minutes
  1579. deleteOnExpire: 'aggressive', // Items will be deleted from this cache when they expire
  1580. storageMode: 'localStorage' // This cache will use `localStorage`.
  1581. });
  1582.  
  1583. return {
  1584. get: function (key) {
  1585. if (dataCache.get(key)) {
  1586. var cart = angular.fromJson(dataCache.get(key));
  1587. return JSON.parse(cart);
  1588. }
  1589. //if ($window.localStorage[key]) {
  1590. // var cart = angular.fromJson($window.localStorage[key]);
  1591. // return JSON.parse(cart);
  1592. //}
  1593. return false;
  1594.  
  1595. },
  1596.  
  1597. set: function (key, val) {
  1598.  
  1599. if (val === undefined) {
  1600. //$window.localStorage.removeItem(key);
  1601. dataCache.remove(key);
  1602. } else {
  1603. dataCache.put(key, angular.toJson(val));
  1604. //$window.localStorage[key] = angular.toJson(val);
  1605. }
  1606. //return $window.localStorage[key];
  1607. return dataCache.get(key);
  1608. },
  1609.  
  1610. emptyCart: function () {
  1611. CacheFactory.destroy('cart');
  1612. }
  1613. }
  1614. }
  1615. ])
  1616. .controller('CartController', [
  1617. '$scope', 'ngCart', 'ngDialog', '$controller', '$rootScope', 'ngCart.lottoyard.api', '$location', 'PaymentSystems', 'ngCart.GetCountryByIpService', 'ngCart.translationService', '$window',
  1618. function ($scope, ngCart, ngDialog, $controller, $rootScope, LottoyardService, $location, PaymentSystems, GetCountryByIpService, translationService, $window) {
  1619. $scope.ngCart = ngCart;
  1620. $scope.allItems = ngCart.getItems();
  1621. $scope.isFirstTimePurchase = $rootScope.isFirstTimePurchase;
  1622. $scope.isAuthenticated = $rootScope.isAuthenticated;
  1623. $scope.paymentSystems = PaymentSystems;
  1624. $scope.extraInfo = "creditcard";
  1625. $scope.promoCode = "";
  1626. $scope.creditcard = {};
  1627. $scope.paymentMethodError = false;
  1628. $scope.country_code = '';
  1629. $scope.signup = { phoneNumber: "", fullname: "", email: "", password: "", mobileNumber: "" };
  1630. $scope.terms = false;
  1631. $scope.fastProcessing = ngCart.getIsFastProcessing();
  1632. $scope.section = { selectionPaymentTemplate: "" };
  1633. $scope.country_codes = CountryCodeNames;
  1634. $scope.country_prefixes = CountryCodePrefixes;
  1635. $scope.language = $rootScope.language;
  1636. $scope.redeemCodeOk = false;
  1637. $scope.redeemCodeWrong = false;
  1638. $scope.showFreeTicket = false;
  1639. $scope.hideEmptyCart = false;
  1640. //$scope.promoCode = ngCart.getReedemCode();
  1641. var currentYear = new Date().getFullYear();
  1642. var legalAgeOfPlay = currentYear - 18;
  1643. $scope.currentYear = currentYear;
  1644. $scope.creditCardExpirationYears = new Array(11).join().split(',').map(function (item, index) { return (index === 0 ? $scope.currentYear : ++$scope.currentYear); });
  1645. $scope.creditCardExpirationMonths = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
  1646. $scope.vipPoints = $rootScope.vipPoints;
  1647. $scope.bonusMoney = $rootScope.bonusMoney;
  1648. $scope.InvalidPhoneErrorMessageSignUp = { display: 'none' };
  1649. $scope.InvalidPasswordErrorMessageSignUp = { display: 'none' };
  1650. $scope.InvalidEmailErrorMessageSignUp = { display: 'none' };
  1651. $scope.InvalidFullnameErrorMessageSignUp = { display: 'none' };
  1652. $scope.InvalidPasswordErrorMessage = { display: 'none' };
  1653. $scope.InvalidEmailErrorMessage = { display: 'none' };
  1654. $scope.phoneInputSignup = "";
  1655. $scope.passwordInputSignup = "";
  1656. $scope.emailInputSignup = "";
  1657. $scope.fullnameInputSignup = "";
  1658. $scope.passwordInputSignin = "";
  1659. $scope.emailInputSignin = "";
  1660. $scope.signupNumberIsChanged = true;
  1661. $scope.birthdayYears = new Array(90).join().split(',').map(function (item, index) { return (legalAgeOfPlay - index); });
  1662. $scope.user = {};
  1663. $scope.user.birthday = {};
  1664. $scope.user.birthday.day = 1;
  1665. $scope.user.birthday.month = $scope.creditCardExpirationMonths[0];
  1666. $scope.user.birthday.year = $scope.birthdayYears[0];
  1667. $scope.daysInMonth = makeArrayOfNumbers(daysInMonth(1, currentYear));
  1668. $scope.toShowAddressFields = false;
  1669. $scope.subtotal = ngCart.totalCost() - ngCart.getReedemBonusAmount();
  1670. $scope.model = {
  1671. isUsingBonusMoney: true
  1672. };
  1673.  
  1674. $scope.cart = {};
  1675. $scope.cart.promoCode = ngCart.getReedemCode();
  1676. $scope.$watch('cart.promoCode', function (newValue, oldValue) {
  1677. if (validatePromoCode(newValue)) {
  1678. ngCart.setReedemCode(newValue);
  1679. }
  1680.  
  1681. getPromoCodeTotal();
  1682. });
  1683.  
  1684. if (ngCart.getProcessor() == "") {
  1685. ngCart.setProcessor("CreditCard");
  1686. }
  1687.  
  1688. $scope.$watch('cart.isCheckedPromoCode', function (newValue, oldValue) {
  1689. if (newValue && validatePromoCode($scope.cart.promoCode)) {
  1690. ngCart.setReedemCode($scope.cart.promoCode);
  1691. } else if (ngCart.getReedemCode() && typeof newValue == "undefined") {
  1692. $scope.cart.isCheckedPromoCode = true;
  1693. } else {
  1694. ngCart.setReedemCode();
  1695. }
  1696.  
  1697. getPromoCodeTotal();
  1698. });
  1699.  
  1700. function setTotalCost() {
  1701. if (!$scope.model.isUsingBonusMoney) {
  1702. $scope.total = ngCart.totalCost() - ngCart.getReedemBonusAmount() < 0 ? 0 : ngCart.totalCost() - ngCart.getReedemBonusAmount();
  1703. } else if ($scope.model.isUsingBonusMoney) {
  1704. $scope.total = ngCart.totalCost() - ngCart.getBonusAmountToUse() - ngCart.getReedemBonusAmount() < 0 ? 0 : ngCart.totalCost() - ngCart.getBonusAmountToUse() - ngCart.getReedemBonusAmount();
  1705. }
  1706. };
  1707.  
  1708. function getPromoCodeTotal() {
  1709. var mapper = new Mapper(ngCart.getCart());
  1710. var data = mapper.PrepareOrder();
  1711.  
  1712. LottoyardService.prepareOrder(data).then(function (resp) {
  1713. prepareOrderResponse(resp);
  1714. setTotalCost();
  1715. }, function (error) {
  1716. console.log(error);
  1717. })
  1718. }
  1719.  
  1720. function validatePromoCode(code) {
  1721. var regex = new RegExp(/[A-z]+-[A-z0-9]+-[A-z0-9]+/);
  1722. return regex.test(code);
  1723. }
  1724.  
  1725. translationService.getTranslation($scope, $rootScope.language);
  1726.  
  1727. $scope.$watch('model.isUsingBonusMoney', function (newValue, oldValue) {
  1728. $scope.ngCart.setUseBonusmoney(newValue);
  1729. var mapper = new Mapper(ngCart.getCart());
  1730. var data = mapper.PrepareOrder();
  1731. LottoyardService.prepareOrder(data).then(function (resp) {
  1732. prepareOrderResponse(resp);
  1733. ngCart.setBonusAmountToUse(resp.BonusAmountAvailable);
  1734. $scope.subtotal = ngCart.totalCost() - ngCart.getReedemBonusAmount();
  1735. $scope.bonus = ngCart.getUseBonusmoney() ? ngCart.getBonusAmountToUse() : 0;
  1736. setTotalCost();
  1737. });
  1738. });
  1739.  
  1740.  
  1741.  
  1742. $scope.$watch(function () {
  1743. return $rootScope.disableBtn;
  1744. }, function () {
  1745. $scope.disableBtn = $rootScope.disableBtn;
  1746. }, true);
  1747.  
  1748. $scope.$watch(function () {
  1749. return $rootScope.progress;
  1750. }, function () {
  1751. $scope.progress = $rootScope.progress;
  1752. }, true);
  1753.  
  1754. if ($scope.isAuthenticated && $scope.isFirstTimePurchase) {
  1755. $scope.showFreeTicket = true;
  1756. $scope.hideEmptyCart = true;
  1757. } else if ($scope.isAuthenticated && !$scope.isFirstTimePurchase) {
  1758. $scope.showFreeTicket = false;
  1759. $scope.hideEmptyCart = false;
  1760. } else {
  1761. $scope.showFreeTicket = false;
  1762. $scope.hideEmptyCart = true;
  1763. }
  1764.  
  1765. if (typeof $rootScope.language === 'undefined' || $rootScope.language === '') {
  1766. $rootScope.language = 'en';
  1767. }
  1768.  
  1769. console.log('lang:', $rootScope.language);
  1770.  
  1771. if (!$scope.isAuthenticated) {
  1772. clearPersonalInfo();
  1773. }
  1774.  
  1775. $scope.redirectToCart = function ($event) {
  1776. $event.preventDefault();
  1777. window.location = '/' + $scope.language + '/cart/';
  1778. }
  1779.  
  1780. $scope.redirectToPlayPageTopJackpot = function () {
  1781. window.location = '/' + $scope.language + '/lottery-ticket/' + $rootScope.topJacktop.LotteryName + '/';
  1782. }
  1783.  
  1784. $scope.initCart = function () {
  1785. //$scope.evenLinesOnlyMessage = ngCart.getEvenLinesOnlyMessage();
  1786. $scope.evenLinesOnlyMessage = JSON.parse(sessionStorage.getItem('showEvenLinesOnly'));
  1787. sessionStorage.setItem('showEvenLinesOnly', false)
  1788.  
  1789. if ($scope.isAuthenticated) {
  1790. LottoyardService.getPersonalDetailsByMemberId(JSON.stringify({ MemberId: "{0}" })).then(function (resp) {
  1791. if (resp.City === "" || resp.Address === "" || resp.ZipCode === "") {
  1792. $scope.toShowAddressFields = true;
  1793. }
  1794.  
  1795. $scope.user.city = resp.City == "" ? $scope.user.city : resp.City;
  1796. $scope.user.address = resp.Address == "" ? $scope.user.address : resp.Address;
  1797. $scope.user.postalCode = resp.ZipCode == "" ? $scope.user.postalCode : resp.ZipCode;
  1798. $scope.creditcard.CardHolderName = resp.FirstName + " " + resp.LastName;
  1799.  
  1800. var birthdayDateApi = new Date(resp.DateOfBirth);
  1801. if (validateEighteenYearsAge(birthdayDateApi)) {
  1802. $scope.user.birthday.day = birthdayDateApi.getDate();
  1803. $scope.user.birthday.month = (birthdayDateApi.getMonth().toString().length === 1 && birthdayDateApi.getMonth() < 9) ? "0" + (birthdayDateApi.getMonth() + 1) : (birthdayDateApi.getMonth() + 1).toString();
  1804. $scope.user.birthday.year = birthdayDateApi.getFullYear();
  1805. $scope.daysInMonth = makeArrayOfNumbers(daysInMonth(parseInt($scope.user.birthday.month), currentYear));
  1806. }
  1807. });
  1808. if (ngCart.getItems().length > 0) {
  1809. //ngCart.setBonusAmountToUse(0);
  1810. var bonusAmountToUse = 0;
  1811. angular.forEach(ngCart.getItems(), function (item) {
  1812. var productId = item.getProductType();
  1813. debugger;
  1814. if (productId == 15 || productId == 3) {
  1815. var itemCost = item.getTotalCost();
  1816. bonusAmountToUse += item.getTotalCost();
  1817. }
  1818.  
  1819. if (ngCart.getIsFastProcessing()) {
  1820. bonusAmountToUse += ngCart.getFastProcessingTax();
  1821. }
  1822. });
  1823. ngCart.setBonusAmountToUse(bonusAmountToUse);
  1824.  
  1825. var items = ngCart.getItems();
  1826. var mapper = new Mapper(ngCart.getCart());
  1827. var data = mapper.PrepareOrder();
  1828. var bonus = ngCart.getBonusAmountToUse();
  1829. debugger;
  1830. LottoyardService.prepareOrder(data).then(function (resp) {
  1831. var bonusAfter = ngCart.getBonusAmountToUse();
  1832. debugger;
  1833. prepareOrderResponse(resp);
  1834. if (resp.BonusAmountAvailable > ngCart.totalCost()) {
  1835. ngCart.setBonusAmountToUse(ngCart.totalCost());
  1836. } else {
  1837. ngCart.setBonusAmountToUse(resp.BonusAmountAvailable);
  1838. }
  1839.  
  1840. var res = ngCart.getItems();
  1841. res.forEach(function (item) {
  1842. var test = item.getIsSubscription();
  1843. item.Checked = item.getIsSubscription();
  1844. })
  1845.  
  1846. if (ngCart.getTotalItems() > 0 && $scope.isAuthenticated && (ngCart.getIframePaymentMethods().length === 0 || $scope.extraInfo != 'creditcard' || $scope.creditCard == false)) {
  1847. $scope.section.selectionPaymentTemplate = 'new';
  1848. } else if (ngCart.getTotalItems() > 0 && $scope.isAuthenticated && ngCart.getIframePaymentMethods().length > 0) {
  1849. $scope.section.selectionPaymentTemplate = 'exist';
  1850. }
  1851.  
  1852. setTotalCost();
  1853. });
  1854. }
  1855. } else {
  1856.  
  1857. if (ngCart.getTotalItems() > 0) {
  1858. var res = ngCart.getItems();
  1859. res.forEach(function (item) {
  1860. item.Checked = item.getIsSubscription();
  1861. })
  1862.  
  1863. $scope.section.selectionPaymentTemplate = 'signup';
  1864. if (validatePromoCode($scope.cart.promoCode)) {
  1865. var mapper = new Mapper(ngCart.getCart());
  1866. var data = mapper.PrepareOrder();
  1867. LottoyardService.prepareOrder(data).then(function (resp) {
  1868. prepareOrderResponse(resp);
  1869. })
  1870. }
  1871.  
  1872. setTotalCost();
  1873. }
  1874. }
  1875. };
  1876.  
  1877. $scope.removeItem = function (itemId) {
  1878. var item = itemId;
  1879. if (typeof itemId !== "object") {
  1880. item = ngCart.getItemById(itemId);
  1881. }
  1882.  
  1883. if ((typeof item === "object") && (item !== null)) {
  1884. var guid = item.getGuid();
  1885. if (typeof guid !== 'undefined') {
  1886. var items = ngCart.getItems();
  1887. var itemToRemove = [];
  1888. angular.forEach(items, function (item) {
  1889. if (item.getGuid() === guid) {
  1890. itemToRemove.push(item.getId());
  1891. }
  1892. });
  1893. for (var i = 0; i < itemToRemove.length; i++) {
  1894. ngCart.removeItemById(itemToRemove[i]);
  1895. }
  1896. } else {
  1897. ngCart.removeItemById(item.getId());
  1898. }
  1899. }
  1900.  
  1901. var allGroup = ngCart.getItems().filter(function (item) {
  1902. return item.getProductType() == 3;
  1903. });
  1904.  
  1905. if (allGroup.length == 0) {
  1906. ngCart.setUseBonusmoney(false);
  1907. $scope.model.isUsingBonusMoney = false;
  1908. }
  1909.  
  1910. $scope.initCart();
  1911. };
  1912.  
  1913. $scope.initSignUp = function () {
  1914. console.log('init');
  1915.  
  1916. GetCountryByIpService.getCountryCodeByIp().then(function (data) {
  1917. $scope.signup.countryPhonePrefix = $scope.country_prefixes[data];
  1918. $scope.signup.phoneNumber = $scope.country_prefixes[data];
  1919. $scope.signup.mobileNumber = $scope.country_prefixes[data];
  1920. $scope.signup.countryCode = data;
  1921. $scope.country_code = CountryCodeNames.filter(function (v) { return v.code === data })[0];
  1922. });
  1923. };
  1924.  
  1925. $scope.setPrefix = function (code) {
  1926. $scope.phone_prefix = $scope.country_prefixes[code];
  1927. $scope.signup.phoneNumber = $scope.phone_prefix;
  1928. $scope.signup.mobileNumber = $scope.phone_prefix;
  1929. };
  1930.  
  1931. $scope.beforeCheckOutCall = beforeCheckOutCall;
  1932.  
  1933. $scope.editPaymentMethods = function () {
  1934. $scope.creditCard = false;
  1935. $scope.section.selectionPaymentTemplate = 'new';
  1936. }
  1937.  
  1938. $scope.signin = function ($event, user) {
  1939. $event.preventDefault();
  1940. $scope.signinErrorText = [];
  1941. $scope.InvalidEmailErrorMessage = { display: 'none' };
  1942. $scope.InvalidPasswordErrorMessage = { display: 'none' };
  1943.  
  1944. if (typeof (user) === 'undefined' || user === "") {
  1945. $scope.signinError = true;
  1946. $scope.signinErrorText.push({ ErrorMessage: "Login failed" });
  1947. return;
  1948. } else if (typeof (user.email) === 'undefined' || user.email === "") {
  1949. $scope.signinError = true;
  1950. $scope.signinErrorText.push({ ErrorMessage: "Login failed" });
  1951. return;
  1952. } else if (typeof (user.password) === 'undefined' || user.password === "") {
  1953. $scope.signinError = true;
  1954. $scope.signinErrorText.push({ ErrorMessage: "Login failed" });
  1955. return;
  1956. }
  1957.  
  1958. $scope.signinError = false;
  1959. $scope.errorText = "";
  1960.  
  1961. LottoyardService.signIn(user).then(function (resp) {
  1962. console.log(resp);
  1963. if (resp === "Login failed") {
  1964. $scope.signinError = true;
  1965. $scope.signinErrorText.push({ ErrorMessage: resp });
  1966. } else {
  1967. clearPersonalInfo();
  1968.  
  1969. //GTM functions for tracking.
  1970. GTM_login(resp.MemberId);
  1971.  
  1972. window.location.href = $rootScope.cartUrlWithLang + "?sessionId=" + resp.UserSessionId + "&bta=" + $rootScope.affiliateId;
  1973. }
  1974. });
  1975. }
  1976.  
  1977. $scope.numberChanged = function (e) {
  1978. if (e.phoneNumber != e.countryPhonePrefix) {
  1979. $scope.signupNumberIsChanged = false;
  1980. }
  1981. }
  1982.  
  1983. $scope.passwordFocusIn = function () {
  1984. $scope.signinError = false;
  1985. var email = $scope.emailInputSignin;
  1986. if (email.trim() === '') {
  1987. $scope.InvalidEmailErrorMessage = { display: 'none' };
  1988. return;
  1989. }
  1990.  
  1991. var emailRegex = new RegExp(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/);
  1992. var isValidEmail = email.match(emailRegex)
  1993. if (!isValidEmail) {
  1994. $scope.InvalidEmailErrorMessage = { display: 'block' };
  1995. } else {
  1996. $scope.InvalidEmailErrorMessage = { display: 'none' };
  1997. }
  1998. }
  1999.  
  2000. $scope.emailFocusOut = function (e) {
  2001. $scope.emailInputSignin = e.currentTarget.value.toString();
  2002. }
  2003.  
  2004. $scope.emailFocusIn = function () {
  2005. $scope.signinError = false;
  2006. var password = $scope.passwordInputSignin;
  2007. if (password.trim() === '') {
  2008. $scope.InvalidPasswordErrorMessage = { display: 'none' };
  2009. return;
  2010. }
  2011.  
  2012. if (password.length < 7 || password.length > 20) {
  2013. $scope.InvalidPasswordErrorMessage = { display: 'block' };
  2014. } else {
  2015. $scope.InvalidPasswordErrorMessage = { display: 'none' };
  2016. }
  2017. }
  2018.  
  2019. $scope.passwordFocusOut = function (e) {
  2020. $scope.passwordInputSignin = e.currentTarget.value.toString();
  2021. }
  2022.  
  2023. $scope.phoneFocusInSignUp = function () {
  2024. $scope.signupError = false;
  2025. _passwordValidation($scope.passwordInputSignup);
  2026. _fullnameValidation($scope.fullnameInputSignup);
  2027. _emailValidation($scope.emailInputSignup);
  2028. }
  2029.  
  2030. $scope.phoneFocusOutSignUp = function (e) {
  2031. $scope.phoneInputSignup = e.currentTarget.value.toString();
  2032. }
  2033.  
  2034. $scope.passwordFocusInSignUp = function () {
  2035. $scope.signupError = false;
  2036. _phoneValidation($scope.phoneInputSignup);
  2037. _fullnameValidation($scope.fullnameInputSignup);
  2038. _emailValidation($scope.emailInputSignup);
  2039. }
  2040.  
  2041. $scope.passwordFocusOutSignUp = function (e) {
  2042. $scope.passwordInputSignup = e.currentTarget.value.toString();
  2043. }
  2044.  
  2045. $scope.fullnameFocusInSignUp = function () {
  2046. $scope.signupError = false;
  2047. _phoneValidation($scope.phoneInputSignup);
  2048. _passwordValidation($scope.passwordInputSignup);
  2049. _emailValidation($scope.emailInputSignup);
  2050. }
  2051.  
  2052. $scope.fullnameFocusOutSignUp = function (e) {
  2053. $scope.fullnameInputSignup = e.currentTarget.value.toString();
  2054. }
  2055.  
  2056. $scope.emailFocusInSignUp = function () {
  2057. $scope.signupError = false;
  2058. _phoneValidation($scope.phoneInputSignup);
  2059. _passwordValidation($scope.passwordInputSignup);
  2060. _fullnameValidation($scope.fullnameInputSignup);
  2061. }
  2062.  
  2063. $scope.emailFocusOutSignUp = function (e) {
  2064. $scope.emailInputSignup = e.currentTarget.value.toString();
  2065. }
  2066.  
  2067. $scope.signUp = function ($event, user) {
  2068. $scope.signupErrorText = [];
  2069. $event.preventDefault();
  2070. $scope.InvalidPhoneErrorMessageSignUp = { display: 'none' };
  2071. $scope.InvalidPasswordErrorMessageSignUp = { display: 'none' };
  2072. $scope.InvalidEmailErrorMessageSignUp = { display: 'none' };
  2073. $scope.InvalidFullnameErrorMessageSignUp = { display: 'none' };
  2074.  
  2075. if (typeof (user) === 'undefined') {
  2076. $scope.signupError = true;
  2077. $scope.signupErrorText.push("Error");
  2078. return;
  2079. }
  2080.  
  2081. if (!user.fullname || user.fullname === "") {
  2082. $scope.signupError = true;
  2083. $scope.signupErrorText.push({ ErrorMessage: "Please insert valid full name" });
  2084. return;
  2085. }
  2086.  
  2087. var fullnameRegex = new RegExp(/^[a-zа-я ]{2,20}$/ig);
  2088. if (!user.fullname.match(fullnameRegex)) {
  2089. $scope.signupError = true;
  2090. $scope.signupErrorText.push({ ErrorMessage: "Name must not include numbers and be 2-20 characters" });
  2091. return;
  2092. }
  2093.  
  2094. var emailRegex = new RegExp(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/);
  2095. if (!user.email || !user.email.match(emailRegex)) {
  2096. $scope.signupError = true;
  2097. $scope.signupErrorText.push({ ErrorMessage: "Please insert valid email" });
  2098. return;
  2099. }
  2100.  
  2101. if (!user.password || user.password === "") {
  2102. $scope.signupError = true;
  2103. $scope.signupErrorText.push({ ErrorMessage: "Please insert valid password" });
  2104. return;
  2105. }
  2106.  
  2107. if (user.password.length < 7 || user.password.length > 20) {
  2108. $scope.signupError = true;
  2109. $scope.signupErrorText.push({ ErrorMessage: "Password length must be between 7 to 20 characters" });
  2110. return;
  2111. }
  2112.  
  2113. var phoneRegex = new RegExp(/^[0-9]{6,25}$/);
  2114. var firstInputNumber = user.phoneNumber.match(phoneRegex);
  2115. var secondInputNumber = user.mobileNumber.match(phoneRegex);
  2116. if ((!firstInputNumber && !secondInputNumber) || (!user.phoneNumber && !user.mobileNumber)) {
  2117. $scope.signupError = true;
  2118. $scope.signupErrorText.push({ ErrorMessage: "Please insert valid phone number" });
  2119. return;
  2120. }
  2121.  
  2122. $scope.signupError = false;
  2123. user.CountryCode = $scope.signup.countryCode;
  2124.  
  2125. var splitedName = user.fullname.split(' ');
  2126. user.firstName = splitedName[0];
  2127. if (splitedName.length > 1) {
  2128. user.lastName = splitedName.slice(1).join(' ');
  2129. }
  2130. user.email = user.email.trim();
  2131. user.affiliateId = $rootScope.affiliateId;
  2132. if (!$scope.signupError) {
  2133. LottoyardService.signUp(user).then(function (resp) {
  2134. console.log(resp);
  2135. if (typeof (resp.UserSessionId) !== 'undefined') {
  2136. clearPersonalInfo();
  2137. sessionStorage.setItem('firepixel', 'https://go.icelotto.com/dynamicpixels/LeadRegistered/?userId=' + resp.MemberId + '&IsoCountry=' + resp.isoCountry);
  2138.  
  2139. //GTM functions for tracking.
  2140. GTM_signup(resp.MemberId);
  2141.  
  2142. window.location.href = $rootScope.cartUrlWithLang + "?sessionId=" + resp.UserSessionId + "&bta=" + $rootScope.affiliateId;
  2143. } else {
  2144. $scope.signupError = true;
  2145. if (Array.isArray(resp)) {
  2146. $scope.signupErrorText = resp;
  2147. } else {
  2148. var err = { ErrorMessage: resp };
  2149. $scope.signupErrorText.push(err);
  2150. }
  2151. }
  2152. });
  2153. }
  2154. }
  2155.  
  2156. $scope.paymentSelect = function (payment) {
  2157. console.log(payment);
  2158.  
  2159. if (($scope.creditCard == true || typeof $scope.creditCard === 'undefined') && ngCart.getIframePaymentMethods().length > 0 && payment.name == 'creditcard') {
  2160. $scope.section.selectionPaymentTemplate = "exist";
  2161. } else {
  2162. $scope.section.selectionPaymentTemplate = "new";
  2163. }
  2164.  
  2165. ngCart.setProcessor(payment.processor);
  2166.  
  2167. if (payment.needmoreinfo) {
  2168. //load div
  2169.  
  2170. if ((ngCart.getAmountToPay() < 2) && (payment.name != "creditcard")) {
  2171. paymentSelect();
  2172. }
  2173. $scope.extraInfo = payment.name;
  2174. return;
  2175. }
  2176. paymentSelect();
  2177. }
  2178.  
  2179. $scope.paymentSelectMoreInfo = function ($event, phoneOrEmail) {
  2180. $event.preventDefault();
  2181. //debugger;
  2182. var test = ngCart.getProcessor();
  2183. console.log(phoneOrEmail);
  2184. ngCart.setPhoneOrEmail(phoneOrEmail);
  2185.  
  2186. paymentSelect();
  2187.  
  2188. }
  2189.  
  2190. $scope.submitOrderNewCreditCard = function (creditcard, user) {
  2191. $scope.creditCardErrorArr = [];
  2192. $scope.creditCard = false;
  2193. var birthday = new Date(Date.UTC(user.birthday.year, (parseInt(user.birthday.month) - 1), user.birthday.day));
  2194.  
  2195. if (typeof (creditcard) === 'undefined') {
  2196. $scope.creditCard = true;
  2197. return;
  2198. }
  2199. if (!creditcard.terms) {
  2200. $scope.creditCard = true;
  2201. $scope.creditCardErrorArr.push({ ErrorMessage: "Please accept our Terms and Conditions" });
  2202. return;
  2203. }
  2204. if (typeof (creditcard.CardHolderName) === 'undefined' || creditcard.CardHolderName.length < 2) {
  2205. $scope.creditCard = true;
  2206. $scope.creditCardErrorArr.push({ ErrorMessage: "Please type your full name" });
  2207. return;
  2208. }
  2209.  
  2210. if (typeof (creditcard.CreditCardNumber) === 'undefined' || creditcard.CreditCardNumber.length == 0) {
  2211. $scope.creditCard = true;
  2212. $scope.creditCardErrorArr.push({ ErrorMessage: "MissingCreditCard" });
  2213. return false;
  2214. }
  2215.  
  2216. if (typeof (creditcard.CreditCardNumber) === 'undefined' || creditcard.CreditCardNumber.length < 10) {
  2217. $scope.creditCard = true;
  2218. $scope.creditCardErrorArr.push({ ErrorMessage: "Credit card number length is invalid" });
  2219. return;
  2220. }
  2221. if (typeof (creditcard.expiration) === 'undefined') {
  2222. $scope.creditCard = true;
  2223. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert Expiration Date" });
  2224. return;
  2225. }
  2226. if (typeof (creditcard.expiration.year) === 'undefined') {
  2227. $scope.creditCard = true;
  2228. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert Expiration Year" });
  2229. return;
  2230. }
  2231. if (typeof (creditcard.expiration.month) === 'undefined') {
  2232. $scope.creditCard = true;
  2233. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert Expiration Month" });
  2234. return;
  2235. }
  2236. if (typeof (creditcard.Cvv) === 'undefined' || creditcard.Cvv.length < 2) {
  2237. $scope.creditCard = true;
  2238. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert your cvv number" });
  2239. return;
  2240. }
  2241.  
  2242. var lastDay = new Date(parseInt(creditcard.expiration.year), parseInt(creditcard.expiration.month), 0).getDate();
  2243. var expirationDate = creditcard.expiration.year + "-" + creditcard.expiration.month + "-" + lastDay;
  2244.  
  2245. var today = new Date();
  2246. today.setHours(0, 0, 0, 0);
  2247. var creditCardDate = new Date(expirationDate);
  2248. creditCardDate.setHours(0, 0, 0, 0);
  2249.  
  2250. if (creditCardDate < today) {
  2251. $scope.creditCard = true;
  2252. $scope.creditCardErrorArr.push({ ErrorMessage: "Please enter valid card expiration date" });
  2253. return;
  2254. }
  2255.  
  2256. var creditCardForSend = {
  2257. CardHolderName: creditcard.CardHolderName,
  2258. CreditCardNumber: creditcard.CreditCardNumber,
  2259. Cvv: creditcard.Cvv,
  2260. ExpirationDate: expirationDate
  2261. };
  2262.  
  2263. if (!validateAddressFields(user, birthday)) {
  2264. return;
  2265. }
  2266. console.log(creditCardForSend);
  2267.  
  2268. ngCart.setProcessor("CreditCard");
  2269.  
  2270.  
  2271. var mapper = new Mapper(ngCart.getCart(), creditCardForSend);
  2272. var data = mapper.ConfirmOrder();
  2273.  
  2274. //updatePersonalDetails
  2275. var personalDetails = {
  2276. MemberId: "{0}",
  2277. DateOfBirth: birthday,
  2278. Address: user.address,
  2279. City: user.city,
  2280. ZipCode: user.postalCode
  2281. };
  2282.  
  2283. LottoyardService.updatePersonalDetails(JSON.stringify(personalDetails)).then(function (resp) {
  2284. if (resp.Result === "Personal details updated") {
  2285.  
  2286. LottoyardService.submitOrder(data).then(function (resp) {
  2287. console.log(resp);
  2288.  
  2289. if (resp.IsSuccess) {
  2290. window.location = '/' + $rootScope.language + '/ThankYou2/Purchase/' + resp.Pmc + "/" + $rootScope.sessionId + "/" + 1 + "/";
  2291. } else {
  2292. $scope.creditCard = true;
  2293. $scope.creditCardErrorArr.push({ ErrorMessage: resp.ErrorMessage });
  2294. return;
  2295. }
  2296. });
  2297. } else {
  2298. $scope.creditCard = true;
  2299. $scope.creditCardErrorArr.push({ ErrorMessage: resp.ErrorMessage });
  2300. return;
  2301. }
  2302. });
  2303. }
  2304.  
  2305. $scope.submitOrder = function (selectedMethod, terms, user) {
  2306. $scope.creditCardErrorArr = [];
  2307.  
  2308. if (typeof user.birthday === 'undefined' && (typeof user.birthday.day === 'undefined' || typeof user.birthday.month === 'undefined' || typeof user.birthday.year === 'undefined')) {
  2309. $scope.creditCard = true;
  2310. $scope.creditCardErrorArr.push({
  2311. ErrorMessage: "Please insert valid date of birth"
  2312. });
  2313. return;
  2314. }
  2315. var birthday = new Date(Date.UTC(user.birthday.year, (parseInt(user.birthday.month) - 1), user.birthday.day));
  2316.  
  2317.  
  2318. if (!terms) {
  2319. $scope.creditCard = true;
  2320. $scope.creditCardErrorArr.push({ ErrorMessage: "Please accept our Terms and Conditions" });
  2321.  
  2322. return;
  2323. }
  2324. if (typeof (selectedMethod) === 'undefined' || selectedMethod.MethodId === '') {
  2325. $scope.creditCard = true;
  2326. $scope.creditCardErrorArr.push({ ErrorMessage: "Please select a payment method" });
  2327. return;
  2328. }
  2329.  
  2330. if (ngCart.getItems().length === 0) {
  2331. return;
  2332. }
  2333.  
  2334. if (!validateAddressFields(user, birthday)) {
  2335. return;
  2336. }
  2337.  
  2338. console.log('submit order', ngCart);
  2339.  
  2340. var mapper = new Mapper(ngCart.getCart(), "");
  2341. var data = mapper.ConfirmOrder();
  2342.  
  2343. console.log(data);
  2344.  
  2345. var personalDetails = {
  2346. MemberId: "{0}",
  2347. DateOfBirth: birthday,
  2348. Address: user.address,
  2349. City: user.city,
  2350. ZipCode: user.postalCode
  2351. };
  2352.  
  2353. if ($scope.toShowAddressFields) {
  2354. LottoyardService.updatePersonalDetails(JSON.stringify(personalDetails)).then(function (resp) {
  2355. if (resp.Result === "Personal details updated") {
  2356. submitOrder();
  2357. }
  2358. else {
  2359. $scope.creditCard = true;
  2360. $scope.creditCardErrorArr.push({
  2361. ErrorMessage: resp
  2362. });
  2363. }
  2364. });
  2365. } else {
  2366. submitOrder();
  2367. }
  2368.  
  2369. function submitOrder() {
  2370. LottoyardService.submitOrder(data).then(function (resp) {
  2371. $scope.creditCardErrorArr = [];
  2372. // ngCart.setBonusAmountToUse(0);
  2373. console.log(resp);
  2374. if (resp.IsSuccess) {
  2375. if (ngCart.getProcessor() !== 'CreditCard') {
  2376. if (resp.StatusCode === 0) {
  2377. $("#hiddenclicker").attr("href", resp.Url);
  2378. $("#hiddenclicker").fancybox(
  2379. {
  2380. 'width': '95%',
  2381. 'height': '95%',
  2382. 'autoScale': true,
  2383. 'transitionIn': 'elastic',
  2384. 'transitionOut': 'elastic',
  2385. 'speedIn': 600,
  2386. 'speedOut': 200,
  2387. 'type': 'iframe'
  2388. }).trigger("click");
  2389. } else {
  2390. $scope.creditCard = true;
  2391. if (Array.isArray(resp)) {
  2392. $scope.creditCardErrorArr.push({
  2393. ErrorMessage: resp.ErrorMessage
  2394. });
  2395. } else {
  2396. if (typeof resp.Status !== 'undefined') {
  2397. $scope.creditCardErrorArr.push({
  2398. ErrorMessage: resp.ErrorMessage
  2399. });
  2400. } else {
  2401. $scope.creditCardErrorArr.push({
  2402. ErrorMessage: resp
  2403. });
  2404. }
  2405. }
  2406. }
  2407. } else {
  2408. $rootScope.progress = true;
  2409. window.location = '/' + $rootScope.language + '/ThankYou2/Purchase/' + resp.Pmc + "/" + $rootScope.sessionId + "/" + 1 + "/";
  2410. }
  2411. } else {
  2412. if (resp.StatusCode === 0) {
  2413. $("#hiddenclicker").attr("href", resp.Url);
  2414. $("#hiddenclicker").fancybox(
  2415. {
  2416. 'width': '95%',
  2417. 'height': '95%',
  2418. 'autoScale': true,
  2419. 'transitionIn': 'elastic',
  2420. 'transitionOut': 'elastic',
  2421. 'speedIn': 600,
  2422. 'speedOut': 200,
  2423. 'type': 'iframe'
  2424. }).trigger("click");
  2425. } else {
  2426. $scope.creditCard = true;
  2427. if (Array.isArray(resp)) {
  2428. $scope.creditCardErrorArr.push({
  2429. ErrorMessage: resp[0].ErrorMessage
  2430. });
  2431. } else {
  2432. if (typeof resp.Status !== 'undefined') {
  2433. $scope.creditCardErrorArr.push({
  2434. ErrorMessage: resp.ErrorMessage
  2435. });
  2436. } else {
  2437. $scope.creditCardErrorArr.push({
  2438. ErrorMessage: resp
  2439. });
  2440. }
  2441. }
  2442. }
  2443. }
  2444. });
  2445. }
  2446. }
  2447.  
  2448. $scope.paymentMethodSelected = function paymentMethodSelected(_methodId, _processor) {
  2449. if (typeof (_methodId) !== 'undefined' && typeof (_processor) !== 'undefined') {
  2450. ngCart.setPaymentMethodId(_methodId);
  2451. ngCart.setProcessor(_processor);
  2452.  
  2453. $rootScope.$broadcast('ngCart:change', {});
  2454. console.log('methodId', _methodId);
  2455. }
  2456. }
  2457.  
  2458. $scope.subscriptionChanged = function (_id) {
  2459. var item = ngCart.getItemById(_id);
  2460. if (item.getIsSubscription()) {
  2461. item.setIsSubscription(false);
  2462. } else {
  2463. item.setIsSubscription(true);
  2464. }
  2465.  
  2466. $rootScope.$broadcast('ngCart:change', {});
  2467.  
  2468. $scope.$broadcast('ngCart:itemSubscriptionChanged', { itemid: _id });
  2469. console.log(ngCart);
  2470. }
  2471.  
  2472. $scope.fastProcessingChanged = function () {
  2473. ngCart.setIsFastProcessing(!ngCart.getIsFastProcessing());
  2474. $scope.fastProcessing = ngCart.getIsFastProcessing();
  2475. var items = ngCart.getItems();
  2476. angular.forEach(items, function (item) {
  2477. debugger;
  2478. item.setIsFastProcessing(ngCart.getIsFastProcessing());
  2479. if (ngCart.getIsFastProcessing()) {
  2480. var bonus = ngCart.getBonusAmountToUse();
  2481. ngCart.setBonusAmountToUse(ngCart.getBonusAmountToUse() + ngCart.getFastProcessingTax());
  2482. //item.setTotalCost(item.getTotalCost() + ngCart.getFastProcessingTax());
  2483. //if (ngCart.getAmountToPay() > 0) {
  2484. // ngCart.setAmountToPay(ngCart.getAmountToPay() + ngCart.getFastProcessingTax());
  2485. //}
  2486. } else {
  2487. //var bonus = ngCart.getBonusAmountToUse();
  2488. //item.setTotalCost(item.getTotalCost() - ngCart.getFastProcessingTax());
  2489. //if (ngCart.getAmountToPay() > 0) {
  2490. // ngCart.setAmountToPay(ngCart.getAmountToPay() - ngCart.getFastProcessingTax());
  2491. //}
  2492. }
  2493. });
  2494.  
  2495. var mapper = new Mapper(ngCart.getCart());
  2496. var data = mapper.PrepareOrder();
  2497. debugger
  2498. LottoyardService.prepareOrder(data).then(function (resp) {
  2499. var totalCost = ngCart.totalCost();
  2500. debugger
  2501. if (resp.BonusAmountAvailable < ngCart.totalCost()) {
  2502. ngCart.setBonusAmountToUse(resp.BonusAmountAvailable);
  2503. } else {
  2504. ngCart.setBonusAmountToUse(ngCart.totalCost());
  2505. }
  2506.  
  2507. prepareOrderResponse(resp);
  2508.  
  2509. setTotalCost();
  2510.  
  2511. $rootScope.$broadcast('ngCart:change', {});
  2512. });
  2513. }
  2514.  
  2515. $scope.beforeCheckout = function ($event) {
  2516. $event.preventDefault();
  2517.  
  2518. console.log('before checkout');
  2519. beforeCheckOutCall();
  2520.  
  2521. window.location = $rootScope.cartUrlWithLang;
  2522.  
  2523. }
  2524.  
  2525. $scope.getRandomInt = getRandomInt;
  2526.  
  2527. $scope.addQuantity = function addQuantity(item) {
  2528. if (item.getQuantity() < 1) {
  2529. return;
  2530. }
  2531.  
  2532. item.setQuantity(item.getQuantity() + 1); //service.getProductPriceById = function (productId, draws, lotteryType
  2533.  
  2534. var priceForDraws = LottoyardService.getProductPriceById(item.getProductType(), item.getNumberOfDraws(), item.getLotteryType()).Price;
  2535. var price = priceForDraws * item.getQuantity();
  2536. var discount = 0;
  2537. debugger;
  2538. item.setTotalCost(price - discount);
  2539. //discounts
  2540. item.setTotalDiscount();
  2541.  
  2542. $scope.initCart();
  2543. console.log(ngCart.getAmountToPay());
  2544. //$rootScope.$broadcast('ngCart:change', {});
  2545. }
  2546.  
  2547. $scope.removeQuantity = function removeQuantity(item) {
  2548. if (item.getQuantity() <= 1) {
  2549. return;
  2550. }
  2551. item.setQuantity(item.getQuantity() - 1);
  2552.  
  2553. var priceForDraws = LottoyardService.getProductPriceById(item.getProductType(), item.getNumberOfDraws(), item.getLotteryType()).Price;
  2554. var price = priceForDraws * item.getQuantity();
  2555. var discount = 0;
  2556.  
  2557. //var price = parseFloat(item.getOriginalPrice() * item.getQuantity() * item.getNumberOfDraws()).toFixed(2);
  2558. //var discount = parseFloat(price * item.getDiscount()).toFixed(2);
  2559.  
  2560. debugger;
  2561. item.setTotalCost(price - discount);
  2562. //discounts
  2563. item.setTotalDiscount();
  2564.  
  2565. $scope.initCart();
  2566.  
  2567. // $rootScope.$broadcast('ngCart:change', {});
  2568. }
  2569.  
  2570. $scope.addShare = function addShare(item) {
  2571. if (item.getGroupnoshares() < 150) {
  2572. var currentShares = item.getGroupnoshares();
  2573. item.setGroupnoshares(currentShares + 1);
  2574.  
  2575. var data = LottoyardService.getProductPriceById(item.getProductType(), item.getGroupnodraws(), item.getLotteryType());
  2576.  
  2577. var mapper = new Mapper(ngCart.getCart());
  2578. var test = mapper.PrepareOrder();
  2579. LottoyardService.prepareOrder(test).then(function (resp) {
  2580. if ($scope.isAuthenticated) {
  2581. ngCart.setBonusAmountToUse(resp.BonusAmountAvailable);
  2582. }
  2583.  
  2584. if (item.getGroupdiscount() > 0) {
  2585. var price = this._totalCost + ((this._totalCost / (1 - this._groupdiscount)) * this._groupdiscount);
  2586. var discount = item.getGroupdiscount() * price;
  2587. } else {
  2588. var price = item.getGroupnoshares() * data.Price;
  2589. var discount = 0;
  2590. }
  2591.  
  2592. //if (ngCart.getIsFastProcessing()) {
  2593. // price += data.Vip;
  2594. //}
  2595.  
  2596. debugger;
  2597. item.setTotalCost(price);
  2598. //discounts
  2599. item.setTotalDiscount(discount);
  2600. if (ngCart.getAmountToPay() == 0) {
  2601. ngCart.setAmountToPay(ngCart.totalCost());
  2602. }
  2603.  
  2604. $scope.initCart();
  2605. $rootScope.$broadcast('ngCart:change', {});
  2606. });
  2607. }
  2608.  
  2609.  
  2610.  
  2611. }
  2612.  
  2613. $scope.removeShare = function removeShare(item) {
  2614. if (item.getGroupnoshares() > 1) {
  2615. var currentShares = item.getGroupnoshares();
  2616. item.setGroupnoshares(currentShares - 1);
  2617.  
  2618. var data = LottoyardService.getProductPriceById(item.getProductType(), item.getGroupnodraws(), item.getLotteryType());
  2619.  
  2620. var mapper = new Mapper(ngCart.getCart());
  2621. var test = mapper.PrepareOrder();
  2622. LottoyardService.prepareOrder(test).then(function (resp) {
  2623. if ($scope.isAuthenticated) {
  2624. ngCart.setBonusAmountToUse(resp.BonusAmountAvailable);
  2625. }
  2626.  
  2627. if (item.getGroupdiscount() > 0) {
  2628. var price = this._totalCost + ((this._totalCost / (1 - this._groupdiscount)) * this._groupdiscount);
  2629. var discount = item.getGroupdiscount() * price;
  2630. } else {
  2631. var price = item.getGroupnoshares() * data.Price;
  2632. var discount = 0;
  2633. }
  2634.  
  2635. //if (ngCart.getIsFastProcessing()) {
  2636. // price += data.Vip;
  2637. //}
  2638.  
  2639. debugger;
  2640. item.setTotalCost(price);
  2641.  
  2642. //discounts
  2643. item.setTotalDiscount(discount);
  2644. if (ngCart.getAmountToPay() == 0) {
  2645. ngCart.setAmountToPay(ngCart.totalCost());
  2646. }
  2647.  
  2648. $scope.initCart();
  2649.  
  2650. $rootScope.$broadcast('ngCart:change', {});
  2651. })
  2652. }
  2653.  
  2654. }
  2655.  
  2656.  
  2657.  
  2658. $scope.initpopuppromo = function (promo) {
  2659. if (promo) {
  2660. $scope.promoactive = true;
  2661. }
  2662. }
  2663.  
  2664. $scope.addLine = function addLine(item, lines, isInitCartCall) {
  2665.  
  2666. if (typeof lines === 'undefined') {
  2667. if (item.getEvenLinesOnly()) {
  2668. lines = item.getNumberOfLines() + 2;
  2669. } else {
  2670. lines = item.getNumberOfLines() + 1;
  2671. }
  2672. }
  2673.  
  2674. if (typeof isInitCartCall === 'undefined') {
  2675. isInitCartCall = true;
  2676. }
  2677.  
  2678. if (item.getMaxLines() > item.getNumberOfLines()) {
  2679. //generate random numbers
  2680. var generatedNumbers = [];
  2681. var generatedExtraNumbers = [];
  2682. var maxSelectNumber = item.getSelectNumbers();
  2683. var minSelectNumber = item.getMinSelectNumbers();
  2684. var minSelectExtraNumber = item.getExtraNumbers();
  2685. var maxSelectExtraNumber = item.getMaxExtraNumbers();
  2686.  
  2687. var itemToGenerate = item.getMaxSelectNumbers();
  2688.  
  2689. for (var i = item.getNumberOfLines() ; i < lines; i++) {
  2690. generatedNumbers = [];
  2691. while (generatedNumbers.length < itemToGenerate) {
  2692. var randomnumber = getRandomInt(minSelectNumber, maxSelectNumber);
  2693. var found = false;
  2694. for (var k = 0; k < generatedNumbers.length; k++) {
  2695. if (generatedNumbers[k] === randomnumber) {
  2696. found = true;
  2697. break;
  2698. }
  2699. }
  2700. if (!found) generatedNumbers[generatedNumbers.length] = randomnumber;
  2701. }
  2702.  
  2703. console.log('generatedNumbers', generatedNumbers);
  2704.  
  2705. //check if there are special numbers
  2706.  
  2707. //this is elgordo special numebr must be same
  2708. if (item.getLotteryType() === 10) {
  2709. var getFirstLine = item.getNumbersSantized()[0];
  2710. generatedExtraNumbers.push(getFirstLine.split('#')[1]);
  2711. } else {
  2712.  
  2713. if (item.getMaxExtraNumbers() > 0) {
  2714. var extraNumbersToGenerate = item.getMaxExtraNumbers();
  2715.  
  2716. while (generatedExtraNumbers.length < extraNumbersToGenerate) {
  2717. var randomnumber = getRandomInt(minSelectExtraNumber, maxSelectExtraNumber);
  2718. var found = false;
  2719. for (var k = 0; k < generatedExtraNumbers.length; k++) {
  2720. if (generatedExtraNumbers[k] === randomnumber) {
  2721. found = true;
  2722. break;
  2723. }
  2724. }
  2725. if (!found) generatedExtraNumbers[generatedExtraNumbers.length] = randomnumber;
  2726. }
  2727. }
  2728.  
  2729. console.log('generatedExtraNumbers', generatedExtraNumbers);
  2730. }
  2731. //store it to item
  2732.  
  2733. var newLinesToStore = item.getNumbers() + '|' + generatedNumbers.join(',');
  2734.  
  2735. if (generatedExtraNumbers.length > 0) {
  2736. newLinesToStore += '#' + generatedExtraNumbers.join(',');
  2737. }
  2738.  
  2739. console.log('newLinesToStore', newLinesToStore);
  2740.  
  2741. item.setNumberOfLines(item.getNumberOfLines() + 1);
  2742.  
  2743. //if is navidad - ignore it
  2744. if (item.getProductType() !== 15) {
  2745. item.setNumbers(newLinesToStore);
  2746. item.setNumbersSantized(newLinesToStore);
  2747. }
  2748. }
  2749.  
  2750. console.log(ngCart);
  2751. //calcualte prices
  2752. var data = LottoyardService.getProductPriceByIds(item.getProductType(), item.getNumberOfDraws(), item.getLotteryType(), item.getNumberOfLines());
  2753.  
  2754. if (item.getDiscount() > 0) {
  2755. var price = data.Price + ((data.Price / (1 - item.getDiscount())) * item.getDiscount());
  2756. var discount = item.getDiscount() * price;
  2757. } else {
  2758. var price = data.Price;
  2759. var discount = item.getDiscount() * price;
  2760. }
  2761.  
  2762. debugger;
  2763. item.setTotalCost(price - discount);
  2764. //discounts
  2765. item.setTotalDiscount();
  2766. }
  2767. if (isInitCartCall) {
  2768. $scope.initCart();
  2769. }
  2770.  
  2771. $rootScope.$broadcast('ngCart:change', {});
  2772. }
  2773.  
  2774. $scope.removeLine = function removeLine(item) {
  2775. if (item.getMinLines() !== item.getNumberOfLines()) {
  2776.  
  2777. var lines = item._evenLinesOnly ? 2 : 1;
  2778.  
  2779. item.setNumberOfLines(item.getNumberOfLines() - lines);
  2780.  
  2781. for (var i = 0; i < lines; i++) {
  2782. item.removeLastLine();
  2783. }
  2784.  
  2785. //calculate prices
  2786. var data = LottoyardService.getProductPriceByIds(item.getProductType(), item.getNumberOfDraws(), item.getLotteryType(), item.getNumberOfLines());
  2787.  
  2788. if (item.getDiscount() > 0) {
  2789. var price = data.Price + ((data.Price / (1 - item.getDiscount())) * item.getDiscount());
  2790. var discount = item.getDiscount() * price;
  2791. } else {
  2792. var price = data.Price;
  2793. var discount = item.getDiscount() * price;
  2794. }
  2795.  
  2796.  
  2797. //var price = parseFloat(item.getOriginalPrice() * item.getNumberOfLines() * parseInt(item.getNumberOfDraws())).toFixed(2);
  2798. //var discount = parseFloat(price * item.getDiscount()).toFixed(2);
  2799. debugger;
  2800. item.setTotalCost(price - discount);
  2801. } else if (item.getMinLines() === item.getNumberOfLines()) {
  2802. return;
  2803. }
  2804.  
  2805. $scope.initCart();
  2806.  
  2807. $rootScope.$broadcast('ngCart:change', {});
  2808. }
  2809.  
  2810. $scope.addDraw = function (item) {
  2811. var drawOptions = item.getProductsDrawOptions();
  2812.  
  2813. var currentDraw = 0;
  2814. if (item.getProductType() === 3) {
  2815. currentDraw = item.getGroupnodraws();
  2816. } else {
  2817. currentDraw = item.getNumberOfDraws();
  2818. }
  2819.  
  2820. var nextDraws = drawOptions.filter(function (obj) {
  2821. if ('NumberOfDraws' in obj && typeof (obj.NumberOfDraws) === 'number' && !isNaN(obj.NumberOfDraws) && obj.NumberOfDraws > currentDraw) {
  2822. return true;
  2823. } else {
  2824. return false;
  2825. }
  2826. });
  2827. var nextDraw = nextDraws[0];
  2828. addDraw(item, nextDraw);
  2829. }
  2830.  
  2831. $scope.removeDraw = function removeDraw(item) {
  2832.  
  2833. var drawOptionsNormal = item.getProductsDrawOptions();
  2834. var drawOptions = cleanArray(reverse(drawOptionsNormal));
  2835.  
  2836. var currentDraw = 0;
  2837.  
  2838. if (item.getSelectedTab() === "groupselection" || item.getProductType() === 3) {
  2839. currentDraw = item.getGroupnodraws();
  2840. } else {
  2841. currentDraw = item.getNumberOfDraws();
  2842. }
  2843.  
  2844. var nextDraws = drawOptions.filter(function (obj) {
  2845. if ('NumberOfDraws' in obj && typeof (obj.NumberOfDraws) === 'number' && !isNaN(obj.NumberOfDraws) && obj.NumberOfDraws < currentDraw) {
  2846. return true;
  2847. } else {
  2848. return false;
  2849. }
  2850. });
  2851.  
  2852. if (nextDraws.length > 1) {
  2853. nextDraws = nextDraws.sort(dynamicSortDescending('NumberOfDraws'));
  2854. }
  2855.  
  2856. var nextDraw = nextDraws[0];
  2857.  
  2858. if (typeof nextDraw !== 'undefined' && typeof (nextDraw.MinLines) !== 'undefined' && typeof (nextDraw.MaxLines) !== 'undefined') {
  2859. item.setMinLines(nextDraw.MinLines);
  2860. item.setMaxLines(nextDraw.MaxLines);
  2861. }
  2862.  
  2863. if (item.getProductType() !== 3) {
  2864. if (item.getMinLines() > item.getNumberOfLines()) {
  2865. console.log('generating new lines - remove draw');
  2866. if (item.getMinLines() > item.getNumberOfLines()) {
  2867. $scope.addLine(item, item.getMinLines(), false);
  2868. }
  2869. }
  2870.  
  2871.  
  2872. }
  2873.  
  2874. if (typeof nextDraw !== 'undefined') {
  2875.  
  2876. var price = 0;
  2877. var discount = 0;
  2878.  
  2879. if (item.getProductType() === 3) {
  2880. item.setGroupnodraws(nextDraw.NumberOfDraws);
  2881. item.setGroupdiscount(nextDraw.Discount);
  2882. ngCart.setBonusAmountToUse(0);
  2883. //calculate price
  2884. var data = LottoyardService.getProductPriceById(item.getProductType(), nextDraw.NumberOfDraws, item.getLotteryType());
  2885.  
  2886. var mapper = new Mapper(ngCart.getCart());
  2887. var test = mapper.PrepareOrder();
  2888.  
  2889. LottoyardService.prepareOrder(test).then(function (resp) {
  2890. debugger
  2891. if ($scope.isAuthenticated) {
  2892. ngCart.setBonusAmountToUse(resp.BonusAmountAvailable);
  2893. }
  2894.  
  2895. if (nextDraw.Discount > 0) {
  2896. var test = item.getGroupnoshares();
  2897. price = item.getGroupnoshares() * (data.Price + ((data.Price / (1 - nextDraw.Discount)) * nextDraw.Discount));
  2898. discount = nextDraw.Discount * price;
  2899. } else {
  2900. price = item.getGroupnoshares() * data.Price;
  2901. discount = nextDraw.Discount * price;
  2902. }
  2903.  
  2904. //if (ngCart.getIsFastProcessing()) {
  2905. // price += data.Vip;
  2906. //}
  2907.  
  2908. debugger;
  2909. item.setTotalCost(price);
  2910. item.setTotalDiscount(discount);
  2911. $scope.initCart();
  2912.  
  2913. $rootScope.$broadcast('ngCart:change', {});
  2914. })
  2915. } else if (item.getProductType() === 2 || item.getProductType() === 4 || item.getProductType() === 14) {
  2916. //productId, draws, lotteryType
  2917. item.setNumberOfDraws(nextDraw.NumberOfDraws);
  2918.  
  2919. var data = LottoyardService.getProductPriceById(item.getProductType(), nextDraw.NumberOfDraws, item.getLotteryType());
  2920.  
  2921. price = data.Price * item.getQuantity();
  2922. discount = 0;
  2923.  
  2924. item.setDiscount(nextDraw.Discount);
  2925.  
  2926. debugger;
  2927. item.setTotalCost(price - discount);
  2928. item.setTotalDiscount(discount);
  2929. $scope.initCart();
  2930.  
  2931. $rootScope.$broadcast('ngCart:change', {});
  2932.  
  2933. } else if (item.getProductType() === 1) {
  2934. item.setNumberOfDraws(nextDraw.NumberOfDraws);
  2935.  
  2936. var data = LottoyardService.getProductPriceByIds(item.getProductType(), item.getNumberOfDraws(), item.getLotteryType(), item.getNumberOfLines());
  2937.  
  2938. if (nextDraw.Discount > 0) {
  2939. var price = data.Price + ((data.Price / (1 - nextDraw.Discount)) * nextDraw.Discount);
  2940. var discount = nextDraw.Discount * price;
  2941. } else {
  2942. var price = data.Price;
  2943. var discount = nextDraw.Discount * price;
  2944. }
  2945. item.setDiscount(nextDraw.Discount);
  2946.  
  2947. debugger;
  2948. item.setTotalCost(price - discount);
  2949. item.setTotalDiscount(discount);
  2950. $scope.initCart();
  2951.  
  2952. $rootScope.$broadcast('ngCart:change', {});
  2953. }
  2954.  
  2955. //item.setTotalCost(price - discount);
  2956. //item.setTotalDiscount(discount);
  2957. //$scope.initCart();
  2958.  
  2959. //$rootScope.$broadcast('ngCart:change', {});
  2960. }
  2961. }
  2962.  
  2963. $scope.addShareNavidad = function (item) {
  2964. if (item.getMaxLines() > item.getNumberOfLines()) {
  2965. debugger;
  2966. item.setNumberOfLines(item.getNumberOfLines() + 1);
  2967. var price = item.getNumberOfLines() * item.getOriginalPrice();
  2968. var discount = item.getDiscount() * price;
  2969.  
  2970. debugger;
  2971. item.setTotalCost(price - discount);
  2972.  
  2973. $scope.initCart();
  2974.  
  2975. $rootScope.$broadcast('ngCart:change', {});
  2976. }
  2977. }
  2978.  
  2979. $scope.removeShareNavidad = function (item) {
  2980. if (item.getMinLines() !== item.getNumberOfLines()) {
  2981. item.setNumberOfLines(item.getNumberOfLines() - 1);
  2982.  
  2983. var price = item.getNumberOfLines() * item.getOriginalPrice();
  2984. var discount = item.getDiscount() * price;
  2985.  
  2986. debugger;
  2987. item.setTotalCost(price - discount);
  2988.  
  2989. $scope.initCart();
  2990.  
  2991. $rootScope.$broadcast('ngCart:change', {});
  2992. }
  2993. }
  2994.  
  2995. $scope.editLine = function editLine(index, item) {
  2996. $scope.ngDialogData = {
  2997. item: item,
  2998. line: index
  2999. };
  3000. ngDialog.open({
  3001. template: '/template/ngcart/addnumbers.html',
  3002. scope: $scope,
  3003. controller: $controller('EditLineDialogController', {
  3004. $scope: $scope
  3005. })
  3006. });
  3007.  
  3008. console.log(index, " ", item);
  3009. }
  3010.  
  3011. $scope.popuppromo = function () {
  3012. if ($scope.promoactive !== true) {
  3013. $scope.promoactive = true;
  3014. } else {
  3015. $scope.promoactive = false;
  3016. }
  3017. }
  3018.  
  3019. $scope.promoCodeValidator = function ($event) {
  3020. var key = $event.charCode || $event.keyCode || 0;
  3021. // Auto-format- do not expose the mask as the user begins to type
  3022. if (key !== 8 && key !== 9) {
  3023.  
  3024. if (typeof ($scope.promoCode) !== 'undefined' && $scope.promoCode !== null && $scope.promoCode.length === 3) {
  3025. $scope.promoCode += '-';
  3026. }
  3027. if (typeof ($scope.promoCode) !== 'undefined' && $scope.promoCode !== null && $scope.promoCode.length === 7) {
  3028. $scope.promoCode += '-';
  3029. }
  3030. }
  3031. }
  3032.  
  3033. $scope.showDetail = function (_id) {
  3034. if ($scope.active !== _id) {
  3035. $scope.active = _id;
  3036. } else {
  3037. $scope.active = null;
  3038. }
  3039. };
  3040.  
  3041. $scope.showthetooltip = function (_id) {
  3042. if ($scope.tooltipshown !== _id) {
  3043. $scope.tooltipshown = _id;
  3044. } else {
  3045. $scope.tooltipshown = null;
  3046. }
  3047. };
  3048.  
  3049. $scope.hidethetooltip = function (_id) {
  3050. $scope.tooltipshown = null;
  3051. };
  3052.  
  3053. $scope.showtooltipcart = function (_id) {
  3054. if ($scope.tooltipcart !== _id) {
  3055. $scope.tooltipcart = _id;
  3056. } else {
  3057. $scope.tooltipcart = null;
  3058. }
  3059. };
  3060.  
  3061. $scope.hidetooltipcart = function (_id) {
  3062. $scope.tooltipcart = null;
  3063. };
  3064.  
  3065. $scope.showtooltippay = function (_id) {
  3066. if ($scope.paycart !== _id) {
  3067. $scope.paycart = _id;
  3068. } else {
  3069. $scope.paycart = null;
  3070. }
  3071. };
  3072.  
  3073. $scope.hidetooltippay = function (_id) {
  3074. $scope.paycart = null;
  3075. };
  3076.  
  3077. $scope.submitPromoCode = function ($event, promoCode) {
  3078. $event.preventDefault();
  3079. //$scope.promoCode = null;
  3080. ngCart.setReedemCode(promoCode);
  3081. beforeCheckOutCall();
  3082. }
  3083.  
  3084. $scope.removePromoCode = function () {
  3085. ngCart.setReedemCode("");
  3086. beforeCheckOutCall();
  3087. $scope.popuppromo();
  3088. }
  3089.  
  3090. $scope.updateDaysInMonth = function (month, year) {
  3091. var daysInMonthValue = daysInMonth(parseInt(month), year);
  3092. if ($scope.user.birthday.day > daysInMonthValue) {
  3093. $scope.user.birthday.day = daysInMonthValue;
  3094. }
  3095. $scope.daysInMonth = makeArrayOfNumbers(daysInMonthValue);
  3096. }
  3097.  
  3098. //events
  3099. $scope.$on('ngCart:itemSubscriptionChanged', function (event, data) {
  3100. //get item
  3101. var item = ngCart.getItemById(data.itemid);
  3102. //get draw option
  3103. var drawOptions = item.getProductsDrawOptions();
  3104.  
  3105. //get current draw
  3106. var currentDraw = 0;
  3107. if (item.getSelectedTab() === 'groupselection' || item.getProductType() === 3) {
  3108. currentDraw = item.getGroupnodraws();
  3109. } else {
  3110. currentDraw = item.getNumberOfDraws();
  3111. }
  3112.  
  3113. //get nearest draw option in new subscription type
  3114. var drawOnlyArray = [];
  3115. angular.forEach(drawOptions, function (item) {
  3116. drawOnlyArray.push(item.NumberOfDraws);
  3117. });
  3118.  
  3119. var nextDrawOnly = closest(currentDraw, drawOnlyArray);
  3120.  
  3121. var nextDraw = drawOptions.filter(function (value) {
  3122. if (value.NumberOfDraws === nextDrawOnly) {
  3123. return true;
  3124. }
  3125. });
  3126.  
  3127. addDraw(item, nextDraw[0]);
  3128. console.log(data);
  3129. });
  3130.  
  3131. //private function
  3132. function _phoneValidation(phone) {
  3133. if (phone.trim() === '' || $scope.signupNumberIsChanged) {
  3134. $scope.InvalidPhoneErrorMessageSignUp = { display: 'none' };
  3135. return;
  3136. }
  3137.  
  3138. var phoneRegex = new RegExp(/^[0-9]{6,25}$/);
  3139. var isValidPhone = phone.match(phoneRegex)
  3140. if (!isValidPhone) {
  3141. $scope.InvalidPhoneErrorMessageSignUp = { display: 'block' };
  3142. } else {
  3143. $scope.InvalidPhoneErrorMessageSignUp = { display: 'none' };
  3144. }
  3145. }
  3146.  
  3147. function _passwordValidation(password) {
  3148. if (password.length == 0) {
  3149. $scope.InvalidPasswordErrorMessageSignUp = { display: 'none' };
  3150. return;
  3151. }
  3152.  
  3153. if (password.length < 7 || password.length > 20) {
  3154. $scope.InvalidPasswordErrorMessageSignUp = { display: 'block' };
  3155. } else {
  3156. $scope.InvalidPasswordErrorMessageSignUp = { display: 'none' };
  3157. }
  3158. }
  3159.  
  3160. function _fullnameValidation(fullname) {
  3161. if (fullname.trim() === '') {
  3162. $scope.InvalidFullnameErrorMessageSignUp = { display: 'none' };
  3163. return;
  3164. }
  3165.  
  3166. var fullnameRegex = new RegExp(/^[a-zа-я ]{2,20}$/ig);
  3167. var isValidFullname = fullname.match(fullnameRegex);
  3168. if (!isValidFullname) {
  3169. $scope.InvalidFullnameErrorMessageSignUp = { display: 'block' };
  3170. } else {
  3171. $scope.InvalidFullnameErrorMessageSignUp = { display: 'none' };
  3172. }
  3173. }
  3174.  
  3175. function _emailValidation(email) {
  3176. if (email.trim() === '') {
  3177. $scope.InvalidEmailErrorMessageSignUp = { display: 'none' };
  3178. return;
  3179. }
  3180.  
  3181. var emailRegex = new RegExp(/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/);
  3182. var isValidEmail = email.match(emailRegex)
  3183. if (!isValidEmail) {
  3184. $scope.InvalidEmailErrorMessageSignUp = { display: 'block' };
  3185. } else {
  3186. $scope.InvalidEmailErrorMessageSignUp = { display: 'none' };
  3187. }
  3188. }
  3189.  
  3190. function prepareOrderResponse(resp) {
  3191. ngCart.setIframePaymentMethods(resp.IframePaymentMethods);
  3192. //setting up default method id for drop down
  3193. if (resp.IframePaymentMethods.length > 0 && $scope.extraInfo == 'creditcard') {
  3194. $scope.selectedmethod = resp.IframePaymentMethods[0];
  3195. ngCart.setPaymentMethodId(resp.IframePaymentMethods[0].MethodId);
  3196. ngCart.setProcessor(resp.IframePaymentMethods[0].Processor);
  3197. }
  3198.  
  3199. var totalAmount = ngCart.totalCost();
  3200. if (totalAmount !== resp.AmountToPay) {
  3201. var amount = resp.AmountToPay < 0 ? 0 : resp.AmountToPay;
  3202. ngCart.setAmountToPay(amount);
  3203. console.log("warning prices missmatch!");
  3204. } else {
  3205. var amount = resp.AmountToPay < 0 ? 0 : resp.AmountToPay;
  3206. var bonusAmount = ngCart.getBonusAmountToUse();
  3207. var bonusRedeemCode = ngCart.getReedemBonusAmount();
  3208. if (amount > 0 && bonusAmount > 0 && $scope.model.isUsingBonusMoney) {
  3209. amount = amount - bonusAmount - bonusRedeemCode;
  3210. }
  3211. ngCart.setAmountToPay(amount);
  3212. }
  3213.  
  3214. //setting ReedemBonusAmount
  3215. ngCart.setReedemBonusAmount(resp.ReedemBonusAmount);
  3216. if (resp.ReedemBonusAmount > 0) {
  3217. $scope.redeemCodeOk = true;
  3218. $scope.redeemCodeWrong = false;
  3219.  
  3220. } else {
  3221. $scope.redeemCodeWrong = true;
  3222. $scope.redeemCodeOk = false;
  3223. }
  3224.  
  3225. $rootScope.$broadcast('ngCart:change', {});
  3226. console.log(ngCart);
  3227. }
  3228.  
  3229. function getBonus() {
  3230. var allPrices = ngCart.getItems().filter(function (item) {
  3231. return item.getProductType() == 3;
  3232. });
  3233.  
  3234. var total = 0;
  3235.  
  3236. allPrices.forEach(function (item) {
  3237. total += item.getTotalCost();
  3238. })
  3239.  
  3240. var bonus;
  3241.  
  3242. if (total <= ngCart.getBonusAmountToUse()) {
  3243. bonus = total;
  3244. }
  3245. else {
  3246. bonus = ngCart.getBonusAmountToUse();
  3247. }
  3248.  
  3249. if (bonus < 0) {
  3250. bonus = 0;
  3251. }
  3252.  
  3253. return bonus;
  3254. }
  3255.  
  3256. function clearPersonalInfo() {
  3257. ngCart.setAmountToPay(0);
  3258. ngCart.setIframePaymentMethods("");
  3259. ngCart.setIsFastProcessing(false);
  3260. ngCart.setPaymentMethodId("");
  3261. ngCart.setPhoneOrEmail("");
  3262. ngCart.setProcessor("");
  3263. ngCart.setBonusAmountToUse(0);
  3264. ngCart.setUseBonusmoney(false);
  3265.  
  3266. $rootScope.$broadcast('ngCart:change', {});
  3267. };
  3268.  
  3269. function closest(num, arr) {
  3270. var curr = arr[0];
  3271. var diff = Math.abs(num - curr);
  3272. for (var val = 0; val < arr.length; val++) {
  3273. var newdiff = Math.abs(num - arr[val]);
  3274. if (newdiff < diff) {
  3275. diff = newdiff;
  3276. curr = arr[val];
  3277. }
  3278. }
  3279. return curr;
  3280. }
  3281.  
  3282. function addDraw(item, nextDraw) {
  3283.  
  3284. if (typeof nextDraw !== 'undefined') {
  3285. var price = 0;
  3286. var discount = 0;
  3287. if (item.getSelectedTab() === "groupselection" || item.getProductType() === 3) {
  3288. item.setGroupnodraws(nextDraw.NumberOfDraws);
  3289. ngCart.setBonusAmountToUse(0);
  3290. //calculate price
  3291. var data = LottoyardService.getProductPriceById(item.getProductType(), nextDraw.NumberOfDraws, item.getLotteryType());
  3292.  
  3293. var mapper = new Mapper(ngCart.getCart());
  3294. var test = mapper.PrepareOrder();
  3295. // debugger
  3296. LottoyardService.prepareOrder(test).then(function (resp) {
  3297. debugger
  3298. if ($scope.isAuthenticated) {
  3299. ngCart.setBonusAmountToUse(resp.BonusAmountAvailable);
  3300. }
  3301.  
  3302. if (nextDraw.Discount > 0) {
  3303. var test = item.getGroupnoshares();
  3304. price = item.getGroupnoshares() * (data.Price + ((data.Price / (1 - nextDraw.Discount)) * nextDraw.Discount));
  3305. discount = nextDraw.Discount * price;
  3306. } else {
  3307. price = item.getGroupnoshares() * data.Price;
  3308. discount = nextDraw.Discount * price;
  3309. }
  3310.  
  3311. //if (ngCart.getIsFastProcessing()) {
  3312. // price += data.Vip;
  3313. //}
  3314.  
  3315. debugger;
  3316. item.setTotalCost(price);
  3317. item.setGroupdiscount(nextDraw.Discount);
  3318.  
  3319. //if ($scope.isAuthenticated && ngCart.getBonusAmountToUse() > 0) {
  3320. // var bonus = getBonus();
  3321. // ngCart.setBonusAmountToUse(bonus);
  3322. //}
  3323.  
  3324. item.setMinLines(nextDraw.MinLines);
  3325. item.setMaxLines(nextDraw.MaxLines);
  3326.  
  3327. item.setTotalDiscount(discount);
  3328.  
  3329. $scope.initCart();
  3330.  
  3331. //setTotalCost();
  3332.  
  3333. $rootScope.$broadcast('ngCart:change', {});
  3334. })
  3335.  
  3336.  
  3337. } else if (item.getProductType() === 2 || item.getProductType() === 4 || item.getProductType() === 14) {
  3338. //productId, draws, lotteryType
  3339. var data = LottoyardService.getProductPriceById(item.getProductType(), nextDraw.NumberOfDraws, item.getLotteryType());
  3340. item.setNumberOfDraws(nextDraw.NumberOfDraws);
  3341.  
  3342. price = data.Price * item.getQuantity();
  3343. discount = 0;
  3344.  
  3345. item.setDiscount(nextDraw.Discount);
  3346.  
  3347. item.setMinLines(nextDraw.MinLines);
  3348. item.setMaxLines(nextDraw.MaxLines);
  3349.  
  3350. debugger;
  3351. item.setTotalCost(price - discount);
  3352.  
  3353. item.setTotalDiscount(discount);
  3354.  
  3355. $scope.initCart();
  3356.  
  3357. $rootScope.$broadcast('ngCart:change', {});
  3358.  
  3359. } else if (item.getProductType() === 1) {
  3360. item.setNumberOfDraws(nextDraw.NumberOfDraws);
  3361.  
  3362. //additional check for min lines according subscription rules
  3363. if (nextDraw.MinLines > item.getNumberOfLines()) {
  3364. $scope.addLine(item, nextDraw.MinLines, false);
  3365. }
  3366.  
  3367. //calculate price
  3368.  
  3369. var data = LottoyardService.getProductPriceByIds(item.getProductType(), item.getNumberOfDraws(), item.getLotteryType(), item.getNumberOfLines());
  3370.  
  3371. if (nextDraw.Discount > 0) {
  3372. var price = data.Price + ((data.Price / (1 - nextDraw.Discount)) * nextDraw.Discount);
  3373. var discount = nextDraw.Discount * price;
  3374. } else {
  3375. var price = data.Price;
  3376. var discount = nextDraw.Discount * price;
  3377. }
  3378.  
  3379. item.setDiscount(nextDraw.Discount);
  3380.  
  3381. item.setMinLines(nextDraw.MinLines);
  3382. item.setMaxLines(nextDraw.MaxLines);
  3383.  
  3384. debugger;
  3385. item.setTotalCost(price - discount);
  3386.  
  3387. item.setTotalDiscount(discount);
  3388.  
  3389. $scope.initCart();
  3390.  
  3391. $rootScope.$broadcast('ngCart:change', {});
  3392. }
  3393.  
  3394. //item.setMinLines(nextDraw.MinLines);
  3395. //item.setMaxLines(nextDraw.MaxLines);
  3396.  
  3397. //item.setTotalCost(price - discount);
  3398.  
  3399. //item.setTotalDiscount(discount);
  3400.  
  3401. //$scope.initCart();
  3402.  
  3403. //$rootScope.$broadcast('ngCart:change', {});
  3404. }
  3405. }
  3406.  
  3407. function beforeCheckOutCall() {
  3408. if (ngCart.getItems().length > 0) {
  3409. var data;
  3410.  
  3411. if ($scope.isAuthenticated) {
  3412. var mapper = new Mapper(ngCart.getCart());
  3413. data = mapper.PrepareOrder();
  3414. } else {
  3415. data = getPrepareOrderNotAutorizedUser();
  3416. }
  3417.  
  3418. LottoyardService.prepareOrder(data).then(function (resp) {
  3419. //setting up payment methods
  3420. prepareOrderResponse(resp);
  3421.  
  3422. $rootScope.$broadcast('ngCart:change', {});
  3423. });
  3424. }
  3425. }
  3426.  
  3427. function reverse(array) {
  3428. var result = [];
  3429. var i = null;
  3430. var arrLength = array.length;
  3431. for (i = arrLength - 1; i >= 0; i -= 1) {
  3432. result.push(array[i]);
  3433. }
  3434.  
  3435. return result;
  3436. }
  3437.  
  3438. function cleanArray(actual) {
  3439. var newArray = new Array();
  3440. for (var i = 0; i < actual.length; i++) {
  3441. if (actual[i]) {
  3442. newArray.push(actual[i]);
  3443. }
  3444. }
  3445. return newArray;
  3446. }
  3447.  
  3448. function paymentSelect() {
  3449. var mapper = new Mapper(ngCart.getCart());
  3450. var mappedCart = mapper.ConfirmOrder();
  3451. console.log('mappedCart', mappedCart);
  3452.  
  3453. LottoyardService.submitOrder(mappedCart).then(function (resp) {
  3454. console.log(resp);
  3455. if (resp.IsSuccess) {
  3456. $scope.progress = false;
  3457. window.location = '/' + $rootScope.language + '/ThankYou2/Purchase/' + resp.Pmc + "/" + $rootScope.sessionId + "/" + 1 + "/";
  3458.  
  3459. } else {
  3460. if (resp.StatusCode === 0 && resp.Status === 0) {
  3461. if (ngCart.getProcessor() === 'PayboutiqueYandex') {
  3462. $scope.status = false;
  3463. $window.open(resp.Url, '_blank');
  3464.  
  3465. } else {
  3466. $("#hiddenclicker").attr("href", resp.Url);
  3467. $("#hiddenclicker").fancybox(
  3468. {
  3469. 'width': '95%',
  3470. 'height': '95%',
  3471. 'autoScale': true,
  3472. 'transitionIn': 'elastic',
  3473. 'transitionOut': 'elastic',
  3474. 'speedIn': 600,
  3475. 'speedOut': 200,
  3476. 'type': 'iframe'
  3477. }).trigger("click");
  3478. }
  3479. } else {
  3480. $scope.creditCard = true;
  3481. $scope.creditCardError = resp.ErrorMessage;
  3482. $scope.paymentMethodError = true;
  3483. $scope.paymentMethodErrorText = resp.ErrorMessage;
  3484. }
  3485.  
  3486. }
  3487. });
  3488. };
  3489.  
  3490. function getRandomInt(min, max) {
  3491. return Math.floor(Math.random() * (max - min + 1)) + min;
  3492. };
  3493.  
  3494. function dynamicSortDescending(property) {
  3495. var sortOrder = 1;
  3496. if (property[0] === "-") {
  3497. sortOrder = -1;
  3498. property = property.substr(1);
  3499. }
  3500. return function (a, b) {
  3501. var result = (a[property] > b[property]) ? -1 : (a[property] < b[property]) ? 1 : 0;
  3502. return result * sortOrder;
  3503. }
  3504. }
  3505.  
  3506. function daysInMonth(month, year) {
  3507. return new Date(year, month, 0).getDate();
  3508. }
  3509.  
  3510. function makeArrayOfNumbers(numbers) {
  3511. return new Array(numbers).join().split(',').map(function (item, index) { return (index === 0 ? 1 : ++index); });
  3512. }
  3513.  
  3514. function validateEighteenYearsAge(date) {
  3515. var currentDate = new Date();
  3516. var dateToCheck = new Date(date);
  3517.  
  3518. //checking years
  3519. if ((currentDate.getFullYear() - dateToCheck.getFullYear()) > 18) {
  3520. return true;
  3521. }
  3522. if ((currentDate.getFullYear() - dateToCheck.getFullYear()) === 18) {
  3523. if (dateToCheck.getMonth() < currentDate.getMonth()) {
  3524. return true;
  3525. }
  3526. if (dateToCheck.getMonth() === currentDate.getMonth()) {
  3527. if ((currentDate.getDate() >= dateToCheck.getDate())) {
  3528. return true;
  3529. }
  3530. }
  3531. }
  3532.  
  3533. return false;
  3534. }
  3535.  
  3536. function validateAddressFields(user, birthday) {
  3537. if (typeof user === 'undefined') {
  3538. $scope.creditCard = true;
  3539. $scope.creditCardErrorArr.push({ ErrorMessage: "Enter additional data" });
  3540. return false;
  3541. }
  3542.  
  3543. if (typeof user.birthday === 'undefined' && (typeof user.birthday.day === 'undefined' || typeof user.birthday.month === 'undefined' || typeof user.birthday.year === 'undefined')) {
  3544. $scope.creditCard = true;
  3545. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert valid date of birth" });
  3546. return false;
  3547. }
  3548.  
  3549. if (!validateEighteenYearsAge(birthday)) {
  3550. $scope.creditCard = true;
  3551. $scope.creditCardErrorArr.push({ ErrorMessage: "TransactionDeclinedMustOver18" });
  3552. return false;
  3553. }
  3554.  
  3555. if (typeof user.city === 'undefined' || user.city.length < 3 || user.city.length > 35) {
  3556. $scope.creditCard = true;
  3557. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert valid city" });
  3558. return false;
  3559. }
  3560.  
  3561. if (typeof user.address === 'undefined' || user.address.length < 4 || user.address.length > 35) {
  3562. $scope.creditCard = true;
  3563. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert valid address" });
  3564. return false;
  3565. }
  3566.  
  3567. if (typeof user.postalCode === 'undefined' || user.postalCode.length < 3 || user.postalCode.length > 12) {
  3568. $scope.creditCard = true;
  3569. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert valid postal code" });
  3570. return false;
  3571. }
  3572. return true;
  3573. }
  3574.  
  3575. console.log(ngCart);
  3576. }
  3577. ])
  3578. .controller('RaffleController', [
  3579. '$rootScope', '$scope', 'ngCart', '$timeout', function ($rootScope, $scope, ngCart, $timeout) {
  3580.  
  3581. function Countdown(scope, item) {
  3582. var timer,
  3583. itemId = item.getId(),
  3584. instance = this,
  3585.  
  3586. counterEnd = function () {
  3587. $timeout(function () {
  3588. ngCart.removeItemById(itemId);
  3589.  
  3590. //var
  3591.  
  3592. $scope.initCart();
  3593. //angular.element('#navidad' + itemId).click();
  3594. }, 100);
  3595. };
  3596.  
  3597. function decrementCounter() {
  3598. if (scope.seconds <= 0) {
  3599. counterEnd();
  3600. instance.stop();
  3601. return;
  3602. }
  3603. scope.seconds--;
  3604. if (scope.seconds === 0) {
  3605. scope.isRefreshing = true;
  3606. }
  3607.  
  3608. angular.element('#timer' + itemId).text(convertDate(scope.seconds));
  3609. scope.$apply(); //update the view bindings
  3610. }
  3611.  
  3612. this.start = function () {
  3613. clearInterval(timer);
  3614. if (item.getProductExpire() === 0) {
  3615. return;
  3616. }
  3617. scope.seconds = item.getProductExpire();
  3618.  
  3619. angular.element('#timer' + itemId).text(convertDate(scope.seconds));
  3620.  
  3621. timer = setInterval(decrementCounter.bind(this.timer), 1000);
  3622. };
  3623.  
  3624. this.stop = function () {
  3625. clearInterval(timer);
  3626. }
  3627. }
  3628.  
  3629. var ct;
  3630. $scope.init = function (id) {
  3631. console.log("raffle counter init id:", id);
  3632. var itemCart = ngCart.getItemById(id);
  3633. //create a new event timer and start counting down
  3634. ct = new Countdown($scope, itemCart);
  3635. ct.start();
  3636. };
  3637.  
  3638. function convertDate(t) {
  3639. var days, hours, minutes, seconds;
  3640. //days = Math.floor(t / 86400);
  3641. //t -= days * 86400;
  3642. //hours = Math.floor(t / 3600) % 24;
  3643. //t -= hours * 3600;
  3644. minutes = Math.floor(t / 60) % 60;
  3645. t -= minutes * 60;
  3646. seconds = t % 60;
  3647. return [
  3648. //days + 'd',
  3649. //hours + 'h',
  3650. minutes + 'm',
  3651. seconds + 's'
  3652. ].join(' ');
  3653. };
  3654. }
  3655. ])
  3656. .controller('DepositController', [
  3657. '$rootScope', '$scope', 'ngCart', 'ngCart.lottoyard.api', 'ngCart.translationService', 'PaymentSystems', '$window', function ($rootScope, $scope, ngCart, LottoyardService, translationService, PaymentSystems, $window) {
  3658. $scope.ngCart = ngCart;
  3659. $scope.depositAmount = 0;
  3660. $scope.paymentSystems = PaymentSystems;
  3661. $scope.terms = false;
  3662. $scope.status = "";
  3663. $scope.statusclass = "";
  3664. $scope.section = { selectionPaymentTemplate: "" };
  3665. $scope.extraInfo = "creditcard";
  3666. $scope.promoCode = "";
  3667. $scope.creditcard = {};
  3668. var currentYear = new Date().getFullYear();
  3669. var legalAgeOfPlay = currentYear - 18;
  3670. $scope.currentYear = currentYear;
  3671. $scope.creditCardExpirationYears = new Array(11).join().split(',').map(function (item, index) { return (index === 0 ? $scope.currentYear : ++$scope.currentYear); });
  3672. $scope.creditCardExpirationMonths = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
  3673. $scope.birthdayYears = new Array(90).join().split(',').map(function (item, index) { return (legalAgeOfPlay - index); });
  3674. $scope.updatePaymentMethod = false;
  3675. $scope.methodId = 0;
  3676. $scope.user = {};
  3677. $scope.user.birthday = {};
  3678. $scope.user.birthday.day = 1;
  3679. $scope.user.birthday.month = $scope.creditCardExpirationMonths[0];
  3680. $scope.user.birthday.year = $scope.birthdayYears[0];
  3681. $scope.daysInMonth = makeArrayOfNumbers(daysInMonth(1, currentYear));
  3682. $scope.toShowAddressFields = false;
  3683.  
  3684. translationService.getTranslation($scope, $rootScope.language);
  3685.  
  3686. $scope.initDepositPage = function () {
  3687.  
  3688. if ($scope.isAuthenticated) {
  3689.  
  3690. var data = JSON.stringify({ MemberId: "{0}" });
  3691.  
  3692. LottoyardService.getPersonalDetailsByMemberId(data).then(function (resp) {
  3693. if (resp.City === "" || resp.Address === "" || resp.ZipCode === "") {
  3694. $scope.toShowAddressFields = true;
  3695. }
  3696. $scope.user.city = resp.City;
  3697. $scope.user.address = resp.Address;
  3698. $scope.user.postalCode = resp.ZipCode;
  3699.  
  3700. var birthdayDateApi = new Date(resp.DateOfBirth);
  3701. if (validateEighteenYearsAge(birthdayDateApi)) {
  3702. $scope.user.birthday.day = birthdayDateApi.getDate();
  3703. $scope.user.birthday.month = (birthdayDateApi.getMonth().toString().length === 1 && birthdayDateApi.getMonth() < 9) ? "0" + (birthdayDateApi.getMonth() + 1) : (birthdayDateApi.getMonth() + 1).toString();
  3704. $scope.user.birthday.year = birthdayDateApi.getFullYear();
  3705. $scope.daysInMonth = makeArrayOfNumbers(daysInMonth(parseInt($scope.user.birthday.month), currentYear));
  3706. }
  3707. });
  3708.  
  3709. LottoyardService.getMemberPaymentMethods(data).then(function (resp) {
  3710. ngCart.setIframePaymentMethods(resp);
  3711. //setting up default method id for drop down
  3712. if (resp.length > 0) {
  3713. $scope.selectedmethod = resp[0];
  3714. ngCart.setPaymentMethodId(resp[0].MethodId);
  3715. ngCart.setProcessor(resp[0].Processor);
  3716. }
  3717.  
  3718. if ($scope.isAuthenticated && ngCart.getIframePaymentMethods().length === 0) {
  3719. $scope.section.selectionPaymentTemplate = 'new';
  3720. } else if ($scope.isAuthenticated && ngCart.getIframePaymentMethods().length > 0) {
  3721. $scope.section.selectionPaymentTemplate = 'exist';
  3722. }
  3723. });
  3724. } else {
  3725. $scope.section.selectionPaymentTemplate = 'signup';
  3726. }
  3727. };
  3728.  
  3729. $rootScope.initPaymentUpdate = function (methodId) {
  3730. $scope.methodId = methodId;
  3731. var data = JSON.stringify({ MemberId: "{0}" });
  3732.  
  3733. LottoyardService.getPaymentMethod(data).then(function (resp) {
  3734. ngCart.setIframePaymentMethods(resp);
  3735. if (resp.length > 0) {
  3736. $scope.setPaymentMethod(resp, methodId);
  3737. }
  3738.  
  3739.  
  3740. });
  3741. };
  3742.  
  3743. $scope.deletePaymentMethod = function (memberId, processorId) {
  3744.  
  3745. var data = {
  3746. Id: memberId,
  3747. SessionId: "{0}",
  3748. MemberId: "{0}",
  3749. ProcessorApi: ngCart.getProcessor()
  3750. };
  3751.  
  3752. LottoyardService.deletePaymentMethod(JSON.stringify(data)).then(function (resp) {
  3753. console.log(resp);
  3754. if (resp.hasOwnProperty("Result")) {
  3755. window.location.replace('/my-account/paymentmethods');
  3756. } else {
  3757. return;
  3758. }
  3759. });
  3760.  
  3761. };
  3762.  
  3763. $scope.addPaymentMethod = function (creditcard) {
  3764. $scope.creditCardErrorArr = [];
  3765. $scope.creditCard = false;
  3766. // debugger;
  3767. if (!validateCreditCard(creditcard)) {
  3768. return;
  3769. }
  3770.  
  3771. var lastDay = new Date(parseInt(creditcard.expiration.year), parseInt(creditcard.expiration.month), 0).getDate();
  3772. var expirationDate = creditcard.expiration.year + "-" + creditcard.expiration.month + "-" + lastDay;
  3773.  
  3774. var data = {
  3775. Id: $scope.updatePaymentMethod ? $scope.methodId : 0,
  3776. SessionId: "{0}",
  3777. MemberId: "{0}",
  3778. ProcessorApi: ngCart.getProcessor(),
  3779. CardType: _getCreditCardType(creditcard.CreditCardNumber),
  3780. CreditCardNumber: $scope.updatePaymentMethod ? null : creditcard.CreditCardNumber,
  3781. Cvv: creditcard.Cvv,
  3782. ExpirationDate: expirationDate,
  3783. CardHolderName: creditcard.CardHolderName
  3784.  
  3785. };
  3786.  
  3787. LottoyardService.addPaymentMethod(JSON.stringify(data)).then(function (resp) {
  3788. console.log(resp);
  3789. if (resp.hasOwnProperty("Result")) {
  3790. window.location.replace('/my-account/paymentmethods');
  3791. } else {
  3792. $scope.creditCard = true;
  3793. $scope.creditCardErrorArr.push({ ErrorMessage: resp[0].ErrorMessage });
  3794. return;
  3795. }
  3796. });
  3797. };
  3798.  
  3799. $scope.setPaymentMethod = function (response, methodId) {
  3800. //debugger;
  3801. angular.forEach(response, function (obj, index) {
  3802. if (obj.Id == methodId) {
  3803. $scope.updatePaymentMethod = true;
  3804. $scope.creditcard.expiration = {};
  3805. $scope.creditcard.CardHolderName = obj.CardHolderName;
  3806. $scope.creditcard.CreditCardNumber = "************" + obj.CreditCardNumber;
  3807. $scope.creditcard.ExpirationDate = obj.ExpirationDate;
  3808. var date = new Date(obj.ExpirationDate);
  3809. $scope.creditcard.expiration.year = date.getFullYear();
  3810. $scope.creditcard.expiration.month = ("0" + (date.getMonth() + 1)).slice(-2);
  3811. $scope.creditcard.Cvv = obj.Cvv;
  3812. }
  3813. });
  3814. };
  3815.  
  3816. $scope.paymentMethodSelected = function (_methodId, _processor) {
  3817. ngCart.setPaymentMethodId(_methodId);
  3818. ngCart.setProcessor(_processor);
  3819.  
  3820. $rootScope.$broadcast('ngCart:change', {});
  3821. console.log('methodId', _methodId);
  3822. };
  3823.  
  3824. $scope.showtooltippay = function (_id) {
  3825. if ($scope.paycart !== _id) {
  3826. $scope.paycart = _id;
  3827. } else {
  3828. $scope.paycart = null;
  3829. }
  3830. };
  3831.  
  3832. $scope.hidetooltippay = function (_id) {
  3833. $scope.paycart = null;
  3834. };
  3835.  
  3836. $scope.depositFunds = function (selectedMethod, depositAmount, terms, user) {
  3837. $scope.creditCard = false;
  3838. $scope.creditCardErrorArr = [];
  3839.  
  3840. if (typeof user.birthday === 'undefined' && (typeof user.birthday.day === 'undefined' || typeof user.birthday.month === 'undefined' || typeof user.birthday.year === 'undefined')) {
  3841. $scope.creditCard = true;
  3842. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert valid date of birth" });
  3843. return;
  3844. }
  3845. var birthday = new Date(Date.UTC(user.birthday.year, (parseInt(user.birthday.month) - 1), user.birthday.day));
  3846.  
  3847. if (!terms) {
  3848. $scope.creditCard = true;
  3849. $scope.statusclass = "error";
  3850. $scope.creditCardErrorArr.push({ ErrorMessage: "Please accept our Terms and Conditions" });
  3851. return;
  3852. }
  3853.  
  3854. if (typeof (selectedMethod) === 'undefined' || selectedMethod.MethodId === '') {
  3855. $scope.creditCard = true;
  3856. $scope.statusclass = "error";
  3857. $scope.creditCardErrorArr.push({ ErrorMessage: "Please select a payment method!" });
  3858. return;
  3859. }
  3860.  
  3861. if (!isNumeric(depositAmount) || depositAmount < 5.00) {
  3862. $scope.creditCard = true;
  3863. $scope.statusclass = "error";
  3864. $scope.creditCardErrorArr.push({
  3865. ErrorMessage: "The Min Deposit Is 5.00EUR"
  3866. });
  3867. return;
  3868. }
  3869.  
  3870. if (!validateAddressFields(user, birthday)) {
  3871. $scope.statusclass = "error";
  3872. return;
  3873. }
  3874.  
  3875. var paymentMethodId = ngCart.getPaymentMethodId();
  3876.  
  3877. if (typeof (paymentMethodId) === 'undefined' || paymentMethodId == null || paymentMethodId === "") paymentMethodId = 0;
  3878.  
  3879. var data = {
  3880. SessionId: "{0}",
  3881. MemberId: "{0}",
  3882. PaymentMethodId: paymentMethodId,
  3883. Amount: depositAmount,
  3884. ProcessorApi: ngCart.getProcessor()
  3885. };
  3886. //updatePersonalDetails
  3887. var personalDetails = {
  3888. MemberId: "{0}",
  3889. DateOfBirth: birthday,
  3890. Address: user.address,
  3891. City: user.city,
  3892. ZipCode: user.postalCode
  3893. };
  3894. if ($scope.toShowAddressFields) {
  3895. LottoyardService.updatePersonalDetails(JSON.stringify(personalDetails)).then(function (resp) {
  3896. if (resp.Result === "Personal details updated") {
  3897. deposit();
  3898. } else {
  3899. $scope.statusclass = "error";
  3900. $scope.creditCard = true;
  3901. $scope.creditCardErrorArr.push({
  3902. ErrorMessage: resp.ErrorMessage
  3903. });
  3904. }
  3905. });
  3906. } else {
  3907. deposit();
  3908. }
  3909.  
  3910. function deposit() {
  3911. LottoyardService.depositFunds(JSON.stringify(data)).then(function (resp) {
  3912. console.log(resp);
  3913. if (resp.IsSuccess) {
  3914. $scope.status = resp.Status;
  3915. $scope.status = "Thank you , your deposit was successful!";
  3916. $scope.statusclass = "ok";
  3917. if (ngCart.getProcessor() !== 'CreditCard') {
  3918.  
  3919. $("#hiddenclicker").attr("href", resp.Url);
  3920. $("#hiddenclicker").fancybox(
  3921. {
  3922. 'width': '95%',
  3923. 'height': '95%',
  3924. 'autoScale': true,
  3925. 'transitionIn': 'elastic',
  3926. 'transitionOut': 'elastic',
  3927. 'speedIn': 600,
  3928. 'speedOut': 200,
  3929. 'type': 'iframe'
  3930. }).trigger("click");
  3931. } else {
  3932. $rootScope.progress = true;
  3933. sessionStorage.setItem("depositAmount", depositAmount);
  3934. window.location = '/' + $rootScope.language + '/ThankYou2/Purchase/' + 0 + "/" + $rootScope.sessionId + "/" + 1 + "/";
  3935. }
  3936.  
  3937. } else {
  3938. $scope.statusclass = "error";
  3939. $scope.creditCard = true;
  3940. if (Array.isArray(resp)) {
  3941. $scope.creditCardErrorArr.push({
  3942. ErrorMessage: resp[0].ErrorMessage
  3943. });
  3944. } else {
  3945. $scope.creditCardErrorArr.push({
  3946. ErrorMessage: resp.ErrorMessage
  3947. });
  3948. }
  3949.  
  3950. }
  3951. });
  3952. }
  3953. };
  3954.  
  3955. $scope.paymentSelect = function (payment) {
  3956. if ($scope.isAuthenticated && payment.name == 'creditcard' && ($scope.creditCard == true || typeof $scope.creditCard == "undefined")) {
  3957. $scope.section.selectionPaymentTemplate = 'exist';
  3958. } else if ($scope.isAuthenticated) {
  3959. $scope.section.selectionPaymentTemplate = 'new';
  3960. }
  3961. console.log(payment);
  3962. ngCart.setProcessor(payment.processor);
  3963. $scope.status = "";
  3964. $scope.extraInfo = payment.name;
  3965. }
  3966.  
  3967. $scope.submitOrderNewCreditCard = function (creditcard, depositAmount, user) {
  3968. $scope.creditCardError = "";
  3969. $scope.creditCardErrorArr = [];
  3970. $scope.creditCard = false;
  3971.  
  3972. if (typeof user.birthday === 'undefined' && (typeof user.birthday.day === 'undefined' || typeof user.birthday.month === 'undefined' || typeof user.birthday.year === 'undefined')) {
  3973. $scope.creditCard = true;
  3974. $scope.creditCardErrorArr.push({
  3975. ErrorMessage: "Please insert valid date of birth"
  3976. });
  3977. return;
  3978. }
  3979. var birthday = new Date(Date.UTC(user.birthday.year, (parseInt(user.birthday.month) - 1), user.birthday.day));
  3980.  
  3981. if (!validateCreditCard(creditcard)) {
  3982. return;
  3983. }
  3984.  
  3985. if (!validateAddressFields(user, birthday)) {
  3986. return;
  3987. }
  3988. if (!isNumeric(depositAmount)) {
  3989. $scope.creditCard = true;
  3990. $scope.creditCardErrorArr.push({
  3991. ErrorMessage: "The Min Deposit Is 5.00EUR"
  3992. });
  3993. return;
  3994. }
  3995. var lastDay = new Date(parseInt(creditcard.expiration.year), parseInt(creditcard.expiration.month), 0).getDate();
  3996. var expirationDate = creditcard.expiration.year + "-" + creditcard.expiration.month + "-" + lastDay;
  3997. creditcard.ExpirationDate = expirationDate;
  3998. ngCart.setProcessor("CreditCard");
  3999. console.log(creditcard);
  4000.  
  4001. var data = {
  4002. SessionId: "{0}",
  4003. MemberId: "{0}",
  4004. Amount: depositAmount,
  4005. ProcessorApi: ngCart.getProcessor(),
  4006. CreditCard: {
  4007. CardType: _getCreditCardType(creditcard.CreditCardNumber),
  4008. CreditCardNumber: creditcard.CreditCardNumber,
  4009. Cvv: creditcard.Cvv,
  4010. ExpirationDate: expirationDate,
  4011. CardHolderName: creditcard.CardHolderName
  4012. }
  4013. };
  4014. //updatePersonalDetails
  4015. var personalDetails = {
  4016. MemberId: "{0}",
  4017. DateOfBirth: birthday,
  4018. Address: user.address,
  4019. City: user.city,
  4020. ZipCode: user.postalCode
  4021. };
  4022.  
  4023. LottoyardService.updatePersonalDetails(JSON.stringify(personalDetails)).then(function (resp) {
  4024. //debugger;
  4025. if (resp.Result === "Personal details updated") {
  4026.  
  4027. LottoyardService.depositFunds(JSON.stringify(data)).then(function (resp) {
  4028. //debugger;
  4029. if (resp.IsSuccess) {
  4030.  
  4031. window.location = '/' + $rootScope.language + '/ThankYou2/Purchase/' + 0 + "/" + $rootScope.sessionId + "/" + 1 + "/";
  4032. } else {
  4033. $scope.creditCard = true;
  4034. $scope.creditCardErrorArr.push({ ErrorMessage: resp.ErrorMessage });
  4035. return;
  4036. }
  4037. });
  4038. } else {
  4039. $scope.creditCard = true;
  4040. $scope.creditCardErrorArr.push({ ErrorMessage: resp.ErrorMessage });
  4041. return;
  4042. }
  4043. });
  4044. }
  4045.  
  4046. $scope.paymentSelectMoreInfo = function ($event, phoneOrEmail, amountToDeposit) {
  4047. $event.preventDefault();
  4048. //debugger;
  4049. console.log(phoneOrEmail);
  4050.  
  4051. ngCart.setPhoneOrEmail(phoneOrEmail);
  4052.  
  4053. paymentSelect(amountToDeposit);
  4054.  
  4055. }
  4056.  
  4057. $scope.editPaymentMethods = function () {
  4058. $scope.creditCard = false;
  4059. $scope.section.selectionPaymentTemplate = 'new';
  4060. }
  4061.  
  4062. $scope.updateDaysInMonth = function (month, year) {
  4063. var daysInMonthValue = daysInMonth(parseInt(month), year);
  4064. if ($scope.user.birthday.day > daysInMonthValue) {
  4065. $scope.user.birthday.day = daysInMonthValue;
  4066. }
  4067. $scope.daysInMonth = makeArrayOfNumbers(daysInMonthValue);
  4068. }
  4069.  
  4070. function daysInMonth(month, year) {
  4071. return new Date(year, month, 0).getDate();
  4072. }
  4073.  
  4074. function makeArrayOfNumbers(numbers) {
  4075. return new Array(numbers).join().split(',').map(function (item, index) { return (index === 0 ? 1 : ++index); });
  4076. }
  4077.  
  4078. function validateEighteenYearsAge(date) {
  4079. // debugger;
  4080. var currentDate = new Date();
  4081. var dateToCheck = new Date(date);
  4082.  
  4083. //checking years
  4084. if ((currentDate.getFullYear() - dateToCheck.getFullYear()) > 18) {
  4085. return true;
  4086. }
  4087. if ((currentDate.getFullYear() - dateToCheck.getFullYear()) === 18) {
  4088. if (dateToCheck.getMonth() < currentDate.getMonth()) {
  4089. return true;
  4090. }
  4091. if (dateToCheck.getMonth() === currentDate.getMonth()) {
  4092. if ((currentDate.getDate() >= dateToCheck.getDate())) {
  4093. return true;
  4094. }
  4095. }
  4096. }
  4097.  
  4098. return false;
  4099. }
  4100.  
  4101. function validateCreditCard(creditcard, expirationDate) {
  4102. if (typeof (creditcard) === 'undefined') {
  4103. $scope.creditCard = true;
  4104. $scope.creditCardErrorArr.push({ ErrorMessage: "MissingCreditCard" });
  4105. return false;
  4106. }
  4107.  
  4108. if (!$scope.updatePaymentMethod) {
  4109.  
  4110. if (!creditcard.terms) {
  4111. $scope.creditCard = true;
  4112. $scope.creditCardErrorArr.push({ ErrorMessage: "Please accept our Terms and Conditions" });
  4113. return false;
  4114. }
  4115.  
  4116. if (typeof (creditcard.CreditCardNumber) === 'undefined' || creditcard.CreditCardNumber.length == 0) {
  4117. $scope.creditCard = true;
  4118. $scope.creditCardErrorArr.push({ ErrorMessage: "MissingCreditCard" });
  4119. return false;
  4120. }
  4121.  
  4122. if (typeof (creditcard.CreditCardNumber) === 'undefined' || creditcard.CreditCardNumber.length < 10) {
  4123. $scope.creditCard = true;
  4124. $scope.creditCardErrorArr.push({ ErrorMessage: "Credit card number length is invalid" });
  4125. return false;
  4126. }
  4127. }
  4128.  
  4129. if (typeof (creditcard.CardHolderName) === 'undefined' || creditcard.CardHolderName.length < 2) {
  4130. $scope.creditCard = true;
  4131. $scope.creditCardErrorArr.push({ ErrorMessage: "Please type your full name" });
  4132. return false;
  4133. }
  4134.  
  4135. if (typeof (creditcard.expiration) === 'undefined') {
  4136. $scope.creditCard = true;
  4137. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert Expiration Date" });
  4138. return false;
  4139. }
  4140.  
  4141. if (typeof (creditcard.expiration.year) === 'undefined') {
  4142. $scope.creditCard = true;
  4143. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert Expiration Year" });
  4144. return false;
  4145. }
  4146.  
  4147. if (typeof (creditcard.expiration.month) === 'undefined') {
  4148. $scope.creditCard = true;
  4149. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert Expiration Month" });
  4150. return false;
  4151. }
  4152.  
  4153. if (typeof (creditcard.Cvv) === 'undefined' || creditcard.Cvv.length < 2) {
  4154. $scope.creditCard = true;
  4155. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert your cvv number" });
  4156. return false;
  4157. }
  4158.  
  4159. var lastDay = new Date(parseInt(creditcard.expiration.year), parseInt(creditcard.expiration.month), 0).getDate();
  4160. var expirationDate = creditcard.expiration.year + "-" + creditcard.expiration.month + "-" + lastDay;
  4161.  
  4162. var today = new Date();
  4163. today.setHours(0, 0, 0, 0);
  4164.  
  4165. var creditCardDate = new Date(expirationDate);
  4166. creditCardDate.setHours(0, 0, 0, 0);
  4167.  
  4168. if (creditCardDate < today) {
  4169. $scope.creditCard = true;
  4170. $scope.creditCardErrorArr.push({ ErrorMessage: "Please enter valid card expiration date" });
  4171. return false;
  4172. }
  4173. return true;
  4174. }
  4175.  
  4176. function isNumeric(obj) {
  4177. return !isNaN(parseFloat(obj)) && isFinite(obj);
  4178. }
  4179.  
  4180. function paymentSelect(amountToDeposit) {
  4181.  
  4182. if (typeof (amountToDeposit) === 'undefined') {
  4183. amountToDeposit = 0;
  4184. }
  4185.  
  4186. var paymentMethodId = ngCart.getPaymentMethodId();
  4187.  
  4188. if (typeof (paymentMethodId) === 'undefined' || paymentMethodId == null || paymentMethodId === "") paymentMethodId = 0;
  4189.  
  4190. var data = {
  4191. SessionId: "{0}",
  4192. MemberId: "{0}",
  4193. PaymentMethodId: paymentMethodId,
  4194. Amount: amountToDeposit,
  4195. ProcessorApi: ngCart.getProcessor(),
  4196. PhoneOrEmail: ngCart.getPhoneOrEmail()
  4197. };
  4198.  
  4199. LottoyardService.depositFunds(JSON.stringify(data)).then(function (resp) {
  4200. $scope.status = false;
  4201. $scope.statusArr = [];
  4202. if (resp.IsSuccess) {
  4203. $scope.status = true;
  4204. if (Array.isArray(resp.Status)) {
  4205. $scope.statusArr = resp.Status;
  4206. } else {
  4207. $scope.statusArr.push({ ErrorMessage: resp.Status });
  4208. }
  4209. if (ngCart.getProcessor() === 'PayboutiqueYandex') {
  4210. $scope.status = false;
  4211. $window.open(resp.Url, '_blank');
  4212.  
  4213. } else if (ngCart.getProcessor() !== 'CreditCard') {
  4214. $scope.status = false;
  4215. $("#hiddenclicker").attr("href", resp.Url);
  4216. $("#hiddenclicker").fancybox(
  4217. {
  4218. 'width': '95%',
  4219. 'height': '95%',
  4220. 'autoScale': true,
  4221. 'transitionIn': 'elastic',
  4222. 'transitionOut': 'elastic',
  4223. 'speedIn': 600,
  4224. 'speedOut': 200,
  4225. 'type': 'iframe'
  4226. }).trigger("click");
  4227. } else {
  4228. window.location = '/' + $rootScope.language + '/ThankYou2/Purchase/' + 0 + "/" + $rootScope.sessionId + "/" + 1 + "/";
  4229. }
  4230.  
  4231. } else {
  4232. $scope.status = true;
  4233. if (Array.isArray(resp.Status)) {
  4234. $scope.statusArr = resp.ErrorMessage;
  4235. } else {
  4236. $scope.statusArr.push({ ErrorMessage: resp.ErrorMessage });
  4237. }
  4238. }
  4239. });
  4240. };
  4241.  
  4242. function validateAddressFields(user, birthday) {
  4243.  
  4244. if (typeof user === 'undefined') {
  4245. $scope.creditCard = true;
  4246. $scope.creditCardErrorArr.push({ ErrorMessage: "Enter additional data" });
  4247. return false;
  4248. }
  4249.  
  4250. if (typeof user.birthday === 'undefined' && (typeof user.birthday.day === 'undefined' || typeof user.birthday.month === 'undefined' || typeof user.birthday.year === 'undefined')) {
  4251. $scope.creditCard = true;
  4252. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert valid date of birth" });
  4253. return false;
  4254. }
  4255.  
  4256. if (!validateEighteenYearsAge(birthday)) {
  4257. $scope.creditCard = true;
  4258. $scope.creditCardErrorArr.push({ ErrorMessage: "TransactionDeclinedMustOver18" });
  4259. return false;
  4260. }
  4261.  
  4262. if (typeof user.city === 'undefined' || user.city.length < 3 || user.city.length > 35) {
  4263. $scope.creditCard = true;
  4264. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert valid city" });
  4265. return false;
  4266. }
  4267.  
  4268. if (typeof user.address === 'undefined' || user.address.length < 4 || user.address.length > 35) {
  4269. $scope.creditCard = true;
  4270. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert valid address" });
  4271. return false;
  4272. }
  4273.  
  4274. if (typeof user.postalCode === 'undefined' || user.postalCode.length < 3 || user.postalCode.length > 12) {
  4275. $scope.creditCard = true;
  4276. $scope.creditCardErrorArr.push({ ErrorMessage: "Please insert valid postal code" });
  4277. return false;
  4278. }
  4279.  
  4280. return true;
  4281. }
  4282.  
  4283. }
  4284. ])
  4285. .controller('EditLineDialogController', [
  4286. '$scope', function ($scope) {
  4287. // debugger;
  4288. var item = $scope.ngDialogData.item;
  4289. var line = $scope.ngDialogData.line;
  4290. $scope.isValidSelectLine = true;
  4291. $scope.isValidExtraLine = true;
  4292.  
  4293. console.log('line', line);
  4294. line++;
  4295. $scope.line = line;
  4296. $scope.item = item;
  4297. console.log('line', line);
  4298. console.log('$scope.line', $scope.line);
  4299.  
  4300. $scope.clickNumber = function (number) {
  4301. // debugger;
  4302.  
  4303. var minSelectNumbers = item.getMinSelectNumbers();
  4304. var maxSelectNumbers = item.getMaxSelectNumbers();
  4305.  
  4306. var totalSelectNumbers = countSelectedNumbersInArray($scope.selectedNumbers);
  4307.  
  4308. console.log('totalSelectNumbers', totalSelectNumbers);
  4309.  
  4310. if (totalSelectNumbers < maxSelectNumbers) {
  4311. if (number.isSelected) {
  4312. number.isSelected = 0;
  4313. } else {
  4314. number.isSelected = 1;
  4315. }
  4316. } else {
  4317. if (number.isSelected) {
  4318. number.isSelected = 0;
  4319. }
  4320. }
  4321.  
  4322. totalSelectNumbers = countSelectedNumbersInArray($scope.selectedNumbers);
  4323.  
  4324. if (totalSelectNumbers < minSelectNumbers) {
  4325. $scope.isValidSelectLine = false;
  4326. } else {
  4327. $scope.isValidSelectLine = true;
  4328. }
  4329. }
  4330.  
  4331. $scope.clickNumberExtra = function (number) {
  4332. //debugger;
  4333. $scope.isValidExtraLine = true;
  4334. var minExtraSelectNumbers = item.getMinExtraNumber();
  4335. var maxExtraSelectNumbers = item.getMaxExtraNumbers();
  4336.  
  4337. var totalExtraSelectNumbers = countSelectedNumbersInArray($scope.selectedNumbersExtra);
  4338.  
  4339. console.log('totalExtraSelectNumbers', totalExtraSelectNumbers);
  4340.  
  4341. if (totalExtraSelectNumbers < maxExtraSelectNumbers) {
  4342. if (number.isSelected) {
  4343. number.isSelected = 0;
  4344. } else {
  4345. number.isSelected = 1;
  4346. }
  4347. } else {
  4348. if (number.isSelected) {
  4349. number.isSelected = 0;
  4350. }
  4351. }
  4352.  
  4353. totalExtraSelectNumbers = countSelectedNumbersInArray($scope.selectedNumbersExtra);
  4354.  
  4355. if (minExtraSelectNumbers !== 0) {
  4356. if (totalExtraSelectNumbers === 0) {
  4357. $scope.isValidExtraLine = false;
  4358. } else if (minExtraSelectNumbers > totalExtraSelectNumbers || totalExtraSelectNumbers < maxExtraSelectNumbers) {
  4359. $scope.isValidExtraLine = false;
  4360. }
  4361. }
  4362.  
  4363.  
  4364. //$scope.isValidLine = true;
  4365. console.log('totalExtraSelectNumbers', totalExtraSelectNumbers);
  4366. }
  4367.  
  4368. function countSelectedNumbersInArray(arr) {
  4369. var totalSelectNumbers = 0;
  4370. arr.filter(function (value) {
  4371. if (value.isSelected) {
  4372. totalSelectNumbers++;
  4373. return false;
  4374. } else {
  4375. return true;
  4376. }
  4377. });
  4378.  
  4379. return totalSelectNumbers;
  4380. }
  4381.  
  4382. function clearSelectedNumbersInArray(arr) {
  4383. return arr.filter(function (value) {
  4384. if (value.isSelected) {
  4385. value.isSelected = 0;
  4386. return false;
  4387. } else {
  4388. return true;
  4389. }
  4390. });
  4391. }
  4392.  
  4393. $scope.checkInput = function (_line) {
  4394. console.log('checkInput');
  4395. //debugger;
  4396. //imame item i line
  4397. var selectedNumbers = countSelectedNumbersInArray($scope.selectedNumbers);
  4398. var selectedExtraNumbers = countSelectedNumbersInArray($scope.selectedNumbersExtra);
  4399. var maxSelectNumbers = item.getMaxSelectNumbers();
  4400.  
  4401. if (selectedNumbers !== maxSelectNumbers) {
  4402. $scope.isValidSelectLine = false;
  4403. return false;
  4404. }
  4405.  
  4406. //todo check if there is extra numvbers
  4407. if (selectedExtraNumbers > 0 || selectedExtraNumbers !== item.getMaxExtraNumbers()) {
  4408. if (selectedExtraNumbers !== item.getMaxExtraNumbers()) {
  4409. $scope.isValidExtraLine = false;
  4410. return false;
  4411. }
  4412. }
  4413.  
  4414. if ($scope.isValidSelectLine && $scope.isValidExtraLine) {
  4415. var currentLineToUpdate = item.getNumbersSantized()[_line];
  4416. console.log(currentLineToUpdate);
  4417.  
  4418. var newLine = [];
  4419.  
  4420. $scope.selectedNumbers.filter(function (value) {
  4421. if (value.isSelected) {
  4422. newLine.push(value.id);
  4423. return false;
  4424. } else {
  4425. return true;
  4426. }
  4427.  
  4428. });
  4429.  
  4430. var newLineToUpdate = newLine.join(',');
  4431.  
  4432. if ($scope.selectedNumbersExtra.length > 0) {
  4433. var newExtraLine = [];
  4434.  
  4435. $scope.selectedNumbersExtra.filter(function (value) {
  4436. if (value.isSelected) {
  4437. newExtraLine.push(value.id);
  4438. return false;
  4439. } else {
  4440. return true;
  4441. }
  4442.  
  4443. });
  4444.  
  4445. newLineToUpdate += '#' + newExtraLine.join(',');
  4446.  
  4447. //elgordo update all lines with same special numbers
  4448. if (item.getLotteryType() === 10) {
  4449. var allLines = item.getNumbersSantized();
  4450.  
  4451. angular.forEach(allLines, function (line, index) {
  4452.  
  4453. var splittedLine = line.split('#');
  4454. var oldLine = splittedLine[0];
  4455. var extraNumber = newExtraLine[0];
  4456. var lineToUpdate = oldLine + '#' + extraNumber;
  4457.  
  4458. item.updateSantizedLine(lineToUpdate, index + 1);
  4459.  
  4460. });
  4461. }
  4462. }
  4463.  
  4464. console.log(newLineToUpdate);
  4465. item.updateSantizedLine(newLineToUpdate, _line);
  4466. }
  4467. return true;
  4468. }
  4469.  
  4470. $scope.clearLine = function () {
  4471. clearSelectedNumbersInArray($scope.selectedNumbers);
  4472. clearSelectedNumbersInArray($scope.selectedNumbersExtra);
  4473.  
  4474. $scope.isValidSelectLine = false;
  4475. }
  4476.  
  4477. $scope.quickpick = function (line) {
  4478. // debugger;
  4479. clearSelectedNumbersInArray($scope.selectedNumbers);
  4480. clearSelectedNumbersInArray($scope.selectedNumbersExtra);
  4481.  
  4482. var maxSelectNumbers = item.getMaxSelectNumbers();
  4483. var maxSelectExtraNumbers = item.getMaxExtraNumbers();
  4484. var startNumber = item.getMinSelectNumbers();
  4485. var startExtraNumber = item.getMinExtraNumber();
  4486. var endNumber = item.getSelectNumbers();
  4487. var endExtraNumbers = item.getExtraNumbers();
  4488.  
  4489. while (countSelectedNumbersInArray($scope.selectedNumbers) < maxSelectNumbers) {
  4490. var number = $scope.getRandomInt(startNumber, endNumber - 1);
  4491.  
  4492. var objNumber = {
  4493. id: 1,
  4494. isSelected: 0
  4495. }
  4496. objNumber.id = number;
  4497. objNumber.isSelected = 1;
  4498. console.log(objNumber);
  4499. console.log('number', number);
  4500. $scope.selectedNumbers[number - 1] = objNumber;
  4501. }
  4502.  
  4503.  
  4504. if (maxSelectExtraNumbers > 0) {
  4505. while (countSelectedNumbersInArray($scope.selectedNumbersExtra) < maxSelectExtraNumbers) {
  4506. var numberExtra = $scope.getRandomInt(startExtraNumber, endExtraNumbers - 1);
  4507.  
  4508. var objNumberExtra = {
  4509. id: 1,
  4510. isSelected: 0
  4511. }
  4512. objNumberExtra.id = numberExtra;
  4513. objNumberExtra.isSelected = 1;
  4514. console.log(objNumberExtra);
  4515. console.log('numberExtra', numberExtra);
  4516. if (item.getLotteryType() === 10) {
  4517. $scope.selectedNumbersExtra[numberExtra] = objNumberExtra;
  4518. } else {
  4519. $scope.selectedNumbersExtra[numberExtra - 1] = objNumberExtra;
  4520. }
  4521.  
  4522. }
  4523. }
  4524. console.log($scope.selectedNumbers);
  4525. console.log($scope.selectedNumbersExtra);
  4526.  
  4527. var selectedNumbers = countSelectedNumbersInArray($scope.selectedNumbers);
  4528. var selectedExtraNumbers = countSelectedNumbersInArray($scope.selectedNumbersExtra);
  4529.  
  4530. if (selectedNumbers === maxSelectNumbers) {
  4531. $scope.isValidSelectLine = true;
  4532. }
  4533. if (selectedExtraNumbers === maxSelectExtraNumbers) {
  4534. $scope.isValidExtraLine = true;
  4535. }
  4536. }
  4537. //debugger;
  4538. line -= 1;
  4539. var selectNumbers = item.getSelectNumbers()
  4540. var selectNumbersExtra = item.getExtraNumbers();
  4541.  
  4542. var selectNumberArray = [];
  4543. var selectNumberExtraArray = [];
  4544. var currentLine = item.getNumbersSantized()[line];
  4545.  
  4546. var emptyLine = false;
  4547.  
  4548. if (typeof currentLine === 'undefined') {
  4549. emptyLine = true;
  4550. }
  4551.  
  4552. var specialNumbers = '';
  4553.  
  4554. if (!emptyLine) {
  4555. var indexOfStartSpecialNumber = currentLine.indexOf('#');
  4556. if (indexOfStartSpecialNumber !== -1) {
  4557. console.log(currentLine);
  4558. specialNumbers = currentLine.substr(parseInt(currentLine.indexOf(('#')) + 1));
  4559.  
  4560. specialNumbers = specialNumbers.split(',');
  4561. console.log(specialNumbers);
  4562. specialNumbers = specialNumbers.map(function (x) { return parseInt(x); });
  4563. }
  4564. var currentLineSplited;
  4565. if (indexOfStartSpecialNumber === -1) {
  4566. currentLineSplited = currentLine.split(',');
  4567. } else {
  4568. currentLineSplited = currentLine.slice(0, indexOfStartSpecialNumber).split(',');
  4569. }
  4570.  
  4571. currentLineSplited = currentLineSplited.map(function (x) { return parseInt(x); });
  4572.  
  4573. console.log(currentLineSplited);
  4574. }
  4575.  
  4576. var startNumber = item.getMinSelectNumbers();
  4577.  
  4578. for (var i = startNumber; i <= selectNumbers; i++) {
  4579. var n = {
  4580. id: i,
  4581. isSelected: 0
  4582. };
  4583. if (!emptyLine) {
  4584. if (currentLineSplited.indexOf(i) >= 0) {
  4585. n.isSelected = 1;
  4586. }
  4587. }
  4588.  
  4589. selectNumberArray.push(n);
  4590. }
  4591.  
  4592. // var startExtraNumber = item.getMinExtraNumber();
  4593. var startExtraNumber = item.getMinExtraNumber();
  4594. //id 10 is Elgordo
  4595. if (item.getMaxExtraNumbers() > 0) {
  4596. for (var j = startExtraNumber; j <= selectNumbersExtra; j++) {
  4597. var extra = {
  4598. id: j,
  4599. isSelected: 0
  4600. };
  4601. if (!emptyLine) {
  4602. if (specialNumbers.indexOf(j) >= 0) {
  4603. extra.isSelected = 1;
  4604. }
  4605. }
  4606.  
  4607. selectNumberExtraArray.push(extra);
  4608. }
  4609. }
  4610. console.log(selectNumberArray);
  4611. $scope.selectedNumbers = selectNumberArray;
  4612. $scope.selectedNumbersExtra = selectNumberExtraArray;
  4613. }
  4614. ])
  4615. .value('version', '1.0.0');
  4616.  
  4617. angular.module('ngCart.directives', ['ngCart.fulfilment'])
  4618. .controller('CartController', ['$scope', 'ngCart', function ($scope, ngCart) {
  4619. $scope.ngCart = ngCart;
  4620.  
  4621. }])
  4622. .directive('ngcartAddtocart', ['ngCart', function (ngCart) {
  4623. return {
  4624. restrict: 'E',
  4625. controller: 'CartController',
  4626. scope: {
  4627. id: '@',
  4628. name: '@',
  4629. quantity: '@',
  4630. quantityMax: '@',
  4631. price: '@',
  4632. data: '='
  4633. },
  4634. transclude: true,
  4635. templateUrl: function (element, attrs) {
  4636. if (typeof attrs.templateUrl == 'undefined') {
  4637. return '/template/ngCart/addtocart.html';
  4638. } else {
  4639. return attrs.templateUrl;
  4640. }
  4641. },
  4642. link: function (scope, element, attrs) {
  4643. scope.attrs = attrs;
  4644. scope.inCart = function () {
  4645. return ngCart.getItemById(attrs.id);
  4646. };
  4647.  
  4648. if (scope.inCart()) {
  4649. scope.q = ngCart.getItemById(attrs.id).getQuantity();
  4650. } else {
  4651. scope.q = parseInt(scope.quantity);
  4652. }
  4653.  
  4654. scope.qtyOpt = [];
  4655. for (var i = 1; i <= scope.quantityMax; i++) {
  4656. scope.qtyOpt.push(i);
  4657. }
  4658. }
  4659.  
  4660. };
  4661. }])
  4662. .directive('ngcartCart', ['$rootScope', function ($rootScope) {
  4663. return {
  4664. restrict: 'E',
  4665. controller: 'CartController',
  4666. scope: {},
  4667. templateUrl: function (element, attrs) {
  4668. if (typeof attrs.templateUrl == 'undefined') {
  4669. return '/template/ngCart/cart.html';
  4670. } else {
  4671. return attrs.templateUrl;
  4672. }
  4673. },
  4674. link: function (scope, element, attrs) {
  4675. // scope.beforeCheckOutCall();
  4676. }
  4677. };
  4678. }])
  4679. .directive('ngcartPayment', ['ngCart', function (ngCart) {
  4680. return {
  4681. restrict: 'E',
  4682. controller: 'CartController',
  4683. scope: {},
  4684. templateUrl: function (element, attrs) {
  4685. return '/template/ngCart/paymentexist.html';
  4686. },
  4687. link: function (scope, element, attrs) {
  4688. }
  4689. };
  4690. }])
  4691. .directive('ngcartPaymentNew', ['ngCart', function (ngCart) {
  4692. return {
  4693. restrict: 'E',
  4694. controller: 'CartController',
  4695. scope: {},
  4696. templateUrl: function (element, attrs) {
  4697. return '/template/ngCart/paymentnew.html';
  4698. },
  4699. link: function (scope, element, attrs) {
  4700. }
  4701. };
  4702. }])
  4703. .directive('amountTabs', ['ngCart', function (ngCart) {
  4704. return {
  4705. restrict: 'E',
  4706. controller: 'CartController',
  4707. scope: {
  4708. isVisible: '=isvisible',
  4709. text: '=text'
  4710. },
  4711. templateUrl: function (element, attrs) {
  4712. return '/template/deposit/amountTabs.html';
  4713. },
  4714. link: function (scope, element, attrs) {
  4715. }
  4716. };
  4717.  
  4718. }])
  4719. .directive('ngcartSignup', ['ngCart', function (ngCart) {
  4720. return {
  4721. restrict: 'E',
  4722. controller: 'CartController',
  4723. scope: {},
  4724. templateUrl: function (element, attrs) {
  4725. //debugger;
  4726. return '/template/ngCart/signup.html';
  4727. },
  4728. link: function (scope, element, attrs) {
  4729. }
  4730. };
  4731. }])
  4732. .directive('ngcartSummary', [function () {
  4733. return {
  4734. restrict: 'E',
  4735. controller: 'CartController',
  4736. scope: {},
  4737. transclude: true,
  4738. templateUrl: function (element, attrs) {
  4739. if (typeof attrs.templateUrl == 'undefined') {
  4740. return '/template/ngCart/summary.html';
  4741. } else {
  4742. return attrs.templateUrl;
  4743. }
  4744. }
  4745. };
  4746. }])
  4747. .directive('ngcartCheckout', [function () {
  4748. return {
  4749. restrict: 'E',
  4750. controller: ('CartController', ['$rootScope', '$scope', 'ngCart', 'fulfilmentProvider', 'ngCart.lottoyard.api', function ($rootScope, $scope, ngCart, fulfilmentProvider, apiService) {
  4751. $scope.ngCart = ngCart;
  4752.  
  4753. $scope.checkout = function ($event) {
  4754. $event.preventDefault();
  4755. // debugger;
  4756. fulfilmentProvider.setService($scope.service);
  4757. fulfilmentProvider.setSettings($scope.settings);
  4758. fulfilmentProvider.checkout()
  4759. .success(function (data, status, headers, config) {
  4760. console.log(data);
  4761. $rootScope.$broadcast('ngCart:checkout_succeeded', data);
  4762. })
  4763. .error(function (data, status, headers, config) {
  4764. $rootScope.$broadcast('ngCart:checkout_failed', {
  4765. statusCode: status,
  4766. error: data
  4767. });
  4768. });
  4769. }
  4770. }]),
  4771. scope: {
  4772. service: '@',
  4773. settings: '='
  4774. },
  4775. transclude: true,
  4776. templateUrl: function (element, attrs) {
  4777. if (typeof attrs.templateUrl == 'undefined') {
  4778. return '/template/ngCart/checkout.html';
  4779. } else {
  4780. return attrs.templateUrl;
  4781. }
  4782. }
  4783. };
  4784. }]);
  4785. angular.module('ngCart.fulfilment', ['lottoYardCacheModule'])
  4786. .run([
  4787. '$rootScope', '$http', function ($rootScope, $http) {
  4788.  
  4789. $http.defaults.transformRequest.push(function (data) {
  4790. $rootScope.progress = true;
  4791. return data;
  4792. });
  4793. $http.defaults.transformResponse.push(function (data) {
  4794. $rootScope.progress = false;
  4795. return data;
  4796. });
  4797. }
  4798. ])
  4799. .service('fulfilmentProvider', [
  4800. '$injector', function ($injector) {
  4801.  
  4802. this._obj = {
  4803. service: undefined,
  4804. settings: undefined
  4805. };
  4806.  
  4807. this.setService = function (service) {
  4808. this._obj.service = service;
  4809. };
  4810.  
  4811. this.setSettings = function (settings) {
  4812. this._obj.settings = settings;
  4813. };
  4814.  
  4815. this.checkout = function () {
  4816.  
  4817. var provider = $injector.get('ngCart.fulfilment.' + this._obj.service);
  4818. return provider.checkout(this._obj.settings);
  4819. }
  4820. }
  4821. ])
  4822. .factory('ngCart.lottoyard.api', [
  4823. '$q', '$log', '$http', 'CacheFactory', 'RESTApiUrl', 'Products', '$timeout', '$interval', 'lottoYardCacheFactory', function ($q, $log, $http, CacheFactory, RESTApiUrl, Products, $timeout, $interval, dataCache) {
  4824.  
  4825. var service = {};
  4826.  
  4827. var MAX_REQUESTS = 5;
  4828. var counterAllLotteriesRules = 1;
  4829. var countergetAllProductsRules = 1;
  4830. var counterProductPrices = 1;
  4831. var counterAllBrandDraws = 1;
  4832.  
  4833. var getAllLotteriesRulesCompleted = false;
  4834. var getAllProductsRulesCompleted = false;
  4835. var getProductPricesCompleted = false;
  4836.  
  4837. function getLotteryFromArrayById(array, id) {
  4838. if (!Array.isArray(array)) {
  4839. array = JSON.parse(array);
  4840. }
  4841. var lottery = array.filter(function (obj) {
  4842. if ('LotteryTypeId' in obj && typeof (obj.LotteryTypeId) === 'number' && obj.LotteryTypeId === id) {
  4843. return true;
  4844. }
  4845. return false;
  4846. });
  4847.  
  4848. return lottery;
  4849. }
  4850.  
  4851. function getProductFromArrayById(array, id) {
  4852. if (!Array.isArray(array)) {
  4853. array = JSON.parse(array);
  4854. }
  4855. var lottery = array.filter(function (obj) {
  4856. if ('ProductId' in obj && typeof (obj.ProductId) === 'number' && obj.ProductId === id) {
  4857. return true;
  4858. }
  4859. return false;
  4860. });
  4861.  
  4862. return lottery;
  4863. }
  4864.  
  4865. function getProductPriceFromArrayById(array, productId, draws, lotteryType) {
  4866. if (!Array.isArray(array)) {
  4867. array = JSON.parse(array);
  4868. }
  4869. return array.filter(function (x) {
  4870. if (x.ProductId === productId && x.NumOfDraws === draws && x.LotteryId === lotteryType) {
  4871. return true;
  4872. } else {
  4873. return false;
  4874. }
  4875. });
  4876. }
  4877.  
  4878. function getProductPriceFromArrayByIds(array, productId, draws, lotteryType, lines) {
  4879. if (!Array.isArray(array)) {
  4880. array = JSON.parse(array);
  4881. }
  4882. return array.filter(function (x) {
  4883. if (x.ProductId === productId && x.NumOfDraws === draws && x.LotteryId === lotteryType && x.Lines === lines) {
  4884. return true;
  4885. } else {
  4886. return false;
  4887. }
  4888. });
  4889. }
  4890.  
  4891. service.getLotteryById = function getLotteryById(id) {
  4892. var idcache = 'lottery-rules';
  4893.  
  4894. if (dataCache.get(idcache)) {
  4895. var cached = dataCache.get(idcache);
  4896. if (!Array.isArray(cached)) {
  4897. cached = JSON.parse(cached);
  4898. }
  4899. //debugger;
  4900. return getLotteryFromArrayById(cached, id)[0];
  4901. } else {
  4902. this.getAllLotteriesRules().then(function (resp) {
  4903. return getLotteryFromArrayById(resp, id)[0];
  4904. });
  4905. }
  4906.  
  4907. };
  4908.  
  4909. service.getProductById = function getLotteryById(id) {
  4910. var idcache = 'product-rules';
  4911.  
  4912. if (dataCache.get(idcache)) {
  4913. var cached = dataCache.get(idcache);
  4914. if (!Array.isArray(cached)) {
  4915. cached = JSON.parse(cached);
  4916. }
  4917. return getProductFromArrayById(cached, id)[0];
  4918. } else {
  4919. this.getAllProductsRules().then(function (resp) {
  4920. return getProductFromArrayById(resp, id)[0];
  4921. });
  4922. }
  4923. };
  4924.  
  4925. service.getAllLotteriesRules = function getAllLotteriesRules() {
  4926.  
  4927. var id = 'lottery-rules';
  4928.  
  4929. var deffered = $q.defer();
  4930.  
  4931. if (dataCache.get(id)) {
  4932. var cached = dataCache.get(id);
  4933. if (!Array.isArray(cached)) {
  4934. cached = JSON.parse(cached);
  4935. }
  4936. deffered.resolve(cached);
  4937. }
  4938. //else {
  4939. // $http({
  4940. // method: 'POST',
  4941. // cache: CacheFactory.get('cachelottoyard'),
  4942. // url: RESTApiUrl,
  4943. // timeout: 2500,
  4944.  
  4945. // data: { action: "globalinfo/lottery-rules", data: "" }
  4946. // }).success(function (data) {
  4947. // var resp;
  4948. // getAllLotteriesRulesCompleted = true;
  4949.  
  4950. // try {
  4951. // resp = JSON.parse(data.d);
  4952.  
  4953. // } catch (e) {
  4954. // console.error('Parsing globalinfo/lottery-rules Error: %s Response: %s', e, data.d);
  4955. // deffered.reject('There was an error');
  4956. // }
  4957.  
  4958. // dataCache.put(id, resp);
  4959.  
  4960. // deffered.resolve(resp);
  4961.  
  4962. // }).error(function (response) {
  4963. // if (counterAllLotteriesRules < MAX_REQUESTS) {
  4964. // $timeout(function () {
  4965. // getAllLotteriesRules();
  4966. // console.log("globalinfo/lottery-rules");
  4967. // }, 2500);
  4968.  
  4969. // counterAllLotteriesRules++;
  4970. // } else {
  4971. // console.warn("Error in getAllProductsRulesCompleted: " + response);
  4972. // deffered.reject('There was an error');
  4973. // }
  4974.  
  4975. // });
  4976. //}
  4977.  
  4978. return deffered.promise;
  4979. };
  4980.  
  4981. service.getAllProductsRules = function getAllProductsRules() {
  4982.  
  4983. var id = 'product-rules';
  4984.  
  4985. var deffered = $q.defer();
  4986.  
  4987. if (dataCache.get(id)) {
  4988. var cached = dataCache.get(id);
  4989. if (!Array.isArray(cached)) {
  4990. cached = JSON.parse(cached);
  4991. }
  4992. deffered.resolve(cached);
  4993. }
  4994. // else {
  4995. // $http({
  4996. // method: 'POST',
  4997. // cache: CacheFactory.get('cachelottoyard'),
  4998. // url: RESTApiUrl,
  4999. // timeout: 2500,
  5000.  
  5001. // data: { action: "globalinfo/product-rules", data: "" }
  5002. // }).success(function (data) {
  5003.  
  5004. // getAllProductsRulesCompleted = true;
  5005. // var resp;
  5006. // try {
  5007. // resp = JSON.parse(data.d);
  5008. // } catch (e) {
  5009. // console.error("Parsing globalinfo/product-rules Error: %s Response: %s ", e, data.d);
  5010. // deffered.reject('There was an error');
  5011. // }
  5012. // dataCache.put(id, resp);
  5013.  
  5014. // deffered.resolve(resp);
  5015.  
  5016. // }).error(function (response) {
  5017. // if (countergetAllProductsRules < MAX_REQUESTS) {
  5018. // console.log('countergetAllProductsRules:' + countergetAllProductsRules);
  5019. // $timeout(function () {
  5020. // service.getAllProductsRules();
  5021. // }, 2500);
  5022.  
  5023. // countergetAllProductsRules++;
  5024. // } else {
  5025. // console.warn("Error in getAllProductsRulesCompleted" + response);
  5026. // deffered.reject('There was an error:');
  5027. // }
  5028.  
  5029. // });
  5030. //}
  5031.  
  5032. return deffered.promise;
  5033. };
  5034.  
  5035. service.getFreeTicket = function getFreeTicket() {
  5036.  
  5037. var id = 'free-ticket';
  5038.  
  5039. var data = JSON.stringify({ MemberId: "{0}" });
  5040.  
  5041. var deffered = $q.defer();
  5042.  
  5043. if (dataCache.get(id)) {
  5044. deffered.resolve(dataCache.get(id));
  5045. } else {
  5046. $http({
  5047. method: 'POST',
  5048. cache: CacheFactory.get('cachelottoyard'),
  5049. url: RESTApiUrl,
  5050. timeout: 2000,
  5051.  
  5052. data: {
  5053. action: "playlottery/get-member-free-ticket",
  5054. data: data
  5055. }
  5056. }).success(function (data) {
  5057.  
  5058. //getAllProductsRulesCompleted = true;
  5059.  
  5060. dataCache.put(id, JSON.parse(data.d));
  5061.  
  5062. deffered.resolve(JSON.parse(data.d));
  5063.  
  5064. }).error(function (response) {
  5065. if (countergetAllProductsRules < MAX_REQUESTS) {
  5066. console.log('countergetAllProductsRules:' + countergetAllProductsRules);
  5067. $timeout(service.getAllProductsRules(), 2500);
  5068.  
  5069. countergetAllProductsRules++;
  5070. } else {
  5071. console.warn("Error in getAllProductsRulesCompleted" + response);
  5072. deffered.reject('There was an error:');
  5073. }
  5074.  
  5075. });
  5076. }
  5077.  
  5078. return deffered.promise;
  5079. };
  5080.  
  5081. service.prepareOrder = function (data) {
  5082. console.log(RESTApiUrl);
  5083.  
  5084. var deffered = $q.defer();
  5085. console.log(data);
  5086. $http({
  5087. method: 'POST',
  5088. url: RESTApiUrl,
  5089. data: {
  5090. action: "cashier/prepare-order",
  5091. data: data
  5092. }
  5093. }).success(function (resp) {
  5094. var parsedResp;
  5095. try {
  5096. parsedResp = JSON.parse(resp.d);
  5097. } catch (e) {
  5098. // console.error("Parsing cashier/prepare-order Error: %s Response: %s", e, resp.d);
  5099. deffered.reject('There was an error');
  5100. }
  5101.  
  5102. console.log(parsedResp);
  5103.  
  5104. deffered.resolve(parsedResp);
  5105.  
  5106. }).error(function () {
  5107. deffered.reject();
  5108. });
  5109.  
  5110. return deffered.promise;
  5111. }
  5112.  
  5113. service.submitOrder = function (data) {
  5114. var deffered = $q.defer();
  5115.  
  5116. $http({
  5117. method: 'POST',
  5118. url: RESTApiUrl,
  5119.  
  5120. data: {
  5121. action: "cashier/processor-confirm-order",
  5122. data: data
  5123. }
  5124. }).success(function (dataResp) {
  5125. var resp;
  5126. try {
  5127. resp = JSON.parse(dataResp.d);
  5128. } catch (e) {
  5129. console.error("Parsing cashier/processor-confirm-order Error: %s Response: %s", e, dataResp.d);
  5130. deffered.reject('There was an error');
  5131. }
  5132. console.log(resp);
  5133.  
  5134. deffered.resolve(resp);
  5135.  
  5136. }).error(function () {
  5137.  
  5138. deffered.reject('There was an error');
  5139. });
  5140.  
  5141.  
  5142. return deffered.promise;
  5143. };
  5144.  
  5145. service.getMemberPaymentMethods = function (data) {
  5146.  
  5147. var deffered = $q.defer();
  5148.  
  5149. $http({
  5150. method: 'POST',
  5151. url: RESTApiUrl,
  5152.  
  5153. data: {
  5154. action: "cashier/get-member-payment-methods",
  5155. data: data
  5156. }
  5157. }).success(function (data) {
  5158. var resp;
  5159. try {
  5160. resp = JSON.parse(data.d);
  5161. } catch (e) {
  5162. console.error("Parsing cashier/get-member-payment-methods Error: %s Response: %s", e, data.d);
  5163. deffered.reject('There was an error');
  5164. }
  5165. console.log(resp);
  5166.  
  5167. deffered.resolve(resp);
  5168.  
  5169. }).error(function () {
  5170.  
  5171. deffered.reject('There was an error');
  5172. });
  5173.  
  5174.  
  5175. return deffered.promise;
  5176. };
  5177.  
  5178. service.updatePersonalDetails = function (data) {
  5179. var deffered = $q.defer();
  5180. console.log(RESTApiUrl);
  5181.  
  5182. $http({
  5183. method: 'POST',
  5184. url: RESTApiUrl,
  5185. data: {
  5186. action: "userinfo/update-personal-details",
  5187. data: data
  5188. }
  5189. }).success(function (data) {
  5190. var resp;
  5191. try {
  5192. resp = JSON.parse(data.d);
  5193. } catch (e) {
  5194. console.error("Parsing cashier/deposit-fundss Error: %s Response: %s", e, data);
  5195. deffered.reject('There was an error');
  5196. }
  5197. console.log(resp);
  5198.  
  5199. deffered.resolve(resp);
  5200.  
  5201. }).error(function () {
  5202.  
  5203. deffered.reject('There was an error');
  5204. });
  5205.  
  5206.  
  5207. return deffered.promise;
  5208. };
  5209.  
  5210. service.getPersonalDetailsByMemberId = function (data) {
  5211. var deffered = $q.defer();
  5212.  
  5213. $http({
  5214. method: 'POST',
  5215. url: RESTApiUrl,
  5216. data: {
  5217. action: "userinfo/get-personal-details-by-memberid ",
  5218. data: data
  5219. }
  5220. }).success(function (data) {
  5221. var resp;
  5222. try {
  5223. resp = JSON.parse(data.d);
  5224. } catch (e) {
  5225. console.error("Parsing cashier/deposit-fundss Error: %s Response: %s", e, data);
  5226. deffered.reject('There was an error');
  5227. }
  5228. console.log(resp);
  5229.  
  5230. deffered.resolve(resp);
  5231.  
  5232. }).error(function () {
  5233.  
  5234. deffered.reject('There was an error');
  5235. });
  5236.  
  5237. return deffered.promise;
  5238. };
  5239.  
  5240. service.depositFunds = function (data) {
  5241. var deffered = $q.defer();
  5242.  
  5243. $http({
  5244. method: 'POST',
  5245. url: RESTApiUrl,
  5246. data: {
  5247. action: "cashier/deposit-funds",
  5248. data: data
  5249. }
  5250. }).success(function (data) {
  5251. var resp;
  5252. try {
  5253. resp = JSON.parse(data.d);
  5254. } catch (e) {
  5255. console.error("Parsing cashier/deposit-fundss Error: %s Response: %s", e, data);
  5256. deffered.reject('There was an error');
  5257. }
  5258. console.log(resp);
  5259.  
  5260. deffered.resolve(resp);
  5261.  
  5262. }).error(function () {
  5263.  
  5264. deffered.reject('There was an error');
  5265. });
  5266.  
  5267.  
  5268. return deffered.promise;
  5269. };
  5270.  
  5271. service.signIn = function (data) {
  5272. data = JSON.stringify(data);
  5273. var deffered = $q.defer();
  5274.  
  5275. $http({
  5276. method: 'POST',
  5277. url: RESTApiUrl,
  5278.  
  5279. data: {
  5280. action: "signup/login-internal",
  5281. data: data
  5282. }
  5283. }).success(function (resp) {
  5284. var parsedResp;
  5285. try {
  5286. parsedResp = JSON.parse(resp.d);
  5287. } catch (e) {
  5288. console.error("Parsing cashier/deposit-fundss Error: %s Response: %s", e, resp.d);
  5289. deffered.reject('There was an error');
  5290. }
  5291. console.log(parsedResp);
  5292.  
  5293. deffered.resolve(parsedResp);
  5294.  
  5295. }).error(function () {
  5296. deffered.reject();
  5297. });
  5298.  
  5299. return deffered.promise;
  5300. }
  5301.  
  5302. //here we are adding products support
  5303. if (typeof (Products) !== 'undefined' && Products.length > 0) {
  5304. service.getProductPrices = function getProductPrices() {
  5305. debugger;
  5306. var id = 'product-prices';
  5307. var products = "";
  5308.  
  5309. angular.forEach(Products, function (item) {
  5310. products += item.id + ',';
  5311. });
  5312.  
  5313. var objToSend = JSON.stringify({ ProductIds: products });
  5314.  
  5315. var deffered = $q.defer();
  5316. if (dataCache.get(id)) {
  5317. var cached = dataCache.get(id);
  5318. if (!Array.isArray(cached)) {
  5319. cached = JSON.parse(cached);
  5320. }
  5321. deffered.resolve(cached);
  5322. }
  5323. //else {
  5324. // $http({
  5325. // method: 'POST',
  5326. // cache: CacheFactory.get('cachelottoyard'),
  5327. // url: RESTApiUrl,
  5328. // timeout: 2500,
  5329.  
  5330. // data: { action: "globalinfo/get-prices-by-brand-and-productid", data: objToSend }
  5331. // }).success(function (data) {
  5332. // var resp;
  5333. // try {
  5334. // resp = JSON.parse(data.d);
  5335. // } catch (e) {
  5336. // console.error("Parsing globalinfo/get-prices-by-brand-and-productid Error: %s Response: %s", e, data.d);
  5337. // deffered.reject('There was an error');
  5338. // }
  5339. // getProductPricesCompleted = true;
  5340.  
  5341. // dataCache.put(id, resp);
  5342.  
  5343. // deffered.resolve(resp);
  5344.  
  5345. // console.log(JSON.parse(data.d));
  5346.  
  5347. // }).error(function (response) {
  5348.  
  5349. // if (counterProductPrices < MAX_REQUESTS) {
  5350. // console.log('counterProductPrices:' + counterProductPrices);
  5351.  
  5352. // $timeout(function () {
  5353. // service.getProductPrices();
  5354. // }, 2500);
  5355.  
  5356. // //getProductPrices();
  5357. // counterProductPrices++;
  5358. // } else {
  5359. // console.warn("Error in getProductPricesCompleted: " + response);
  5360. // deffered.reject('There was an error');
  5361. // }
  5362.  
  5363. // });
  5364. //}
  5365.  
  5366. return deffered.promise;
  5367. }
  5368.  
  5369. service.getProductPriceById = function (productId, draws, lotteryType) {
  5370. var idcache = 'product-prices';
  5371. if (dataCache.get(idcache)) {
  5372. var cached = dataCache.get(idcache);
  5373. if (!Array.isArray(cached)) {
  5374. cached = JSON.parse(cached);
  5375. }
  5376. return getProductPriceFromArrayById(cached, productId, draws, lotteryType)[0];
  5377. } else {
  5378. this.getProductPrices().then(function (resp) {
  5379.  
  5380. return getProductPriceFromArrayById(resp, productId, draws, lotteryType)[0];
  5381. });
  5382. }
  5383. };
  5384.  
  5385. service.getProductPriceByIds = function (productId, draws, lotteryType, lines) {
  5386. var idcache = 'product-prices';
  5387.  
  5388. if (dataCache.get(idcache)) {
  5389. var cached = dataCache.get(idcache);
  5390. if (!Array.isArray(cached)) {
  5391. // debugger;
  5392. cached = JSON.parse(cached);
  5393. }
  5394. return getProductPriceFromArrayByIds(cached, productId, draws, lotteryType, lines)[0];
  5395. } else {
  5396. this.getProductPrices().then(function (resp) {
  5397. return getProductPriceFromArrayByIds(resp, productId, draws, lotteryType, lines)[0];
  5398. });
  5399. }
  5400. };
  5401. }
  5402. //signUp
  5403. service.signUp = function (data) {
  5404. data = JSON.stringify(data);
  5405. var deffered = $q.defer();
  5406. console.log(data);
  5407. $http({
  5408. method: 'POST',
  5409. url: RESTApiUrl,
  5410.  
  5411. data: {
  5412. action: "signup/signup-internal",
  5413. data: data
  5414. }
  5415. }).success(function (resp) {
  5416. var parsedResp = null;
  5417. try {
  5418. parsedResp = JSON.parse(resp.d);
  5419. } catch (e) {
  5420. console.error("Parsing signup/signup-internal Error: %s Response: %s", e, resp);
  5421. }
  5422. // console.log(parsedResp);
  5423.  
  5424. deffered.resolve(parsedResp);
  5425.  
  5426. }).error(function () {
  5427. deffered.reject();
  5428. });
  5429.  
  5430. return deffered.promise;
  5431. }
  5432. //get lotteries jackpots
  5433. //get-all-brand-draws
  5434. service.getAllBrandDraws = function getAllBrandDraws() {
  5435. var id = 'get-all-brand-draws';
  5436. var deffered = $q.defer();
  5437.  
  5438. if (dataCache.get(id)) {
  5439. var cached = dataCache.get(id);
  5440. if (!Array.isArray(cached)) {
  5441. cached = JSON.parse(cached);
  5442. }
  5443. deffered.resolve(cached);
  5444. } else {
  5445. $http({
  5446. method: 'POST',
  5447. cache: CacheFactory.get('cachelottoyard'),
  5448. url: RESTApiUrl,
  5449. timeout: 2500,
  5450. data: {
  5451. action: "globalinfo/get-all-brand-draws",
  5452. data: ""
  5453. }
  5454. }).success(function (data) {
  5455. var resp = null;
  5456. try {
  5457. resp = JSON.parse(data.d);
  5458. } catch (e) {
  5459. console.error("Parsing globalinfo/get-all-brand-draws Error: %s Response: %s", e, data.d);
  5460. deffered.reject('There was an error');
  5461. }
  5462. getProductPricesCompleted = true;
  5463.  
  5464. dataCache.put(id, resp);
  5465.  
  5466. deffered.resolve(resp);
  5467.  
  5468. }).error(function (response) {
  5469.  
  5470. if (counterAllBrandDraws < MAX_REQUESTS) {
  5471. console.log('counterAllBrandDraws:' + counterAllBrandDraws);
  5472. $timeout(function () {
  5473. service.getAllBrandDraws();
  5474. }, 2500);
  5475. //getAllBrandDraws();
  5476. counterAllBrandDraws++;
  5477. } else {
  5478. console.warn("Error in counterAllBrandDraws: " + response);
  5479. deffered.reject('There was an error');
  5480. }
  5481. });
  5482. }
  5483.  
  5484. return deffered.promise;
  5485. }
  5486.  
  5487. service.getRaffleTicket = function getRaffleTicket(productId) {
  5488.  
  5489. var deffered = $q.defer();
  5490. var data = JSON.stringify({
  5491. ProductId: productId
  5492. });
  5493.  
  5494. $http({
  5495. method: 'POST',
  5496. url: RESTApiUrl,
  5497. data: {
  5498. action: "playlottery/get-navidad-numbers",
  5499. data: data
  5500. }
  5501. }).success(function (data) {
  5502.  
  5503. deffered.resolve(JSON.parse(data.d));
  5504.  
  5505. }).error(function (response) {
  5506. console.warn("Error in playlottery/get-navidad-numbers" + response);
  5507. deffered.reject('There was an error:');
  5508. });
  5509.  
  5510. return deffered.promise;
  5511. };
  5512.  
  5513. service.getPaymentMethod = function getPaymentMethod(data) {
  5514. var deffered = $q.defer();
  5515.  
  5516. $http({
  5517. method: 'POST',
  5518. url: RESTApiUrl,
  5519. data: {
  5520. action: "userinfo/get-credit-card-methods-by-memberid",
  5521. data: data
  5522. }
  5523. }).success(function (data) {
  5524.  
  5525. deffered.resolve(JSON.parse(data.d));
  5526.  
  5527. }).error(function (response) {
  5528. console.warn("Error in userinfo/get-credit-card-methods-by-memberid" + response);
  5529. deffered.reject('There was an error:');
  5530. });
  5531.  
  5532. return deffered.promise;
  5533. };
  5534.  
  5535. service.deletePaymentMethod = function deletePaymentMethod(data) {
  5536. var deffered = $q.defer();
  5537.  
  5538. $http({
  5539. method: 'POST',
  5540. url: RESTApiUrl,
  5541. data: {
  5542. action: "userinfo/delete-credit-card",
  5543. data: data
  5544. }
  5545. }).success(function (data) {
  5546. var resp;
  5547. try {
  5548. resp = JSON.parse(data.d);
  5549. } catch (e) {
  5550. console.error("Parsing Api delete payment Error: %s Response: %s", e, data);
  5551. deffered.reject('There was an error');
  5552. }
  5553. console.log(resp);
  5554.  
  5555. deffered.resolve(resp);
  5556.  
  5557. }).error(function () {
  5558.  
  5559. deffered.reject('There was an error');
  5560. });
  5561.  
  5562.  
  5563. return deffered.promise;
  5564. };
  5565.  
  5566. service.addPaymentMethod = function addPaymentMethod(data) {
  5567. var deffered = $q.defer();
  5568.  
  5569. $http({
  5570. method: 'POST',
  5571. url: RESTApiUrl,
  5572. data: {
  5573. action: "userinfo/add-update-credit-card",
  5574. data: data
  5575. }
  5576. }).success(function (data) {
  5577. var resp;
  5578. try {
  5579. resp = JSON.parse(data.d);
  5580. } catch (e) {
  5581. console.error("Parsing Api add payment Error: %s Response: %s", e, data);
  5582. deffered.reject('There was an error');
  5583. }
  5584. console.log(resp);
  5585.  
  5586. deffered.resolve(resp);
  5587.  
  5588. }).error(function () {
  5589.  
  5590. deffered.reject('There was an error');
  5591. });
  5592.  
  5593.  
  5594. return deffered.promise;
  5595. };
  5596.  
  5597. return service;
  5598.  
  5599. }
  5600. ])
  5601. .service('ngCart.fulfilment.log', [
  5602. '$q', '$log', 'ngCart', function ($q, $log, ngCart) {
  5603.  
  5604. this.checkout = function () {
  5605.  
  5606. var deferred = $q.defer();
  5607.  
  5608. $log.info(ngCart.toObject());
  5609. deferred.resolve({
  5610. cart: ngCart.toObject()
  5611. });
  5612.  
  5613. return deferred.promise;
  5614.  
  5615. }
  5616.  
  5617. }
  5618. ])
  5619. .service('ngCart.fulfilment.http', [
  5620. '$http', 'ngCart', function ($http, ngCart) {
  5621.  
  5622. this.checkout = function (settings) {
  5623. return $http.post(settings.url,
  5624. {
  5625. data: ngCart.toObject(),
  5626. options: settings.options
  5627. });
  5628. }
  5629. }
  5630. ])
  5631. .service('ngCart.translationService', [
  5632. 'ngCart', '$resource', '$http', function (ngCart, $resource, $http) {
  5633.  
  5634. this.getTranslation = function ($scope, language) {
  5635. var service = this;
  5636. var request = $http({
  5637. method: "GET",
  5638. url: '/Scripts/cartjs/translations/translation_' + language + '.json',
  5639. });
  5640.  
  5641. request.then(function (resp) {
  5642. $scope.translation = resp.data;
  5643. }, function (resp) {
  5644. if (resp.status === 404) {
  5645. service.getTranslation($scope, 'en');
  5646. }
  5647. });
  5648. //var languageFilePath = '/Scripts/cartjs/translations/translation_' + language + '.json';
  5649. //$resource(languageFilePath).get().$promise.then(function (data) {
  5650. // debugger;
  5651. // $scope.translation = data;
  5652. //});
  5653. };
  5654. }
  5655. ])
  5656. .service('ngCart.fulfilment.lottoyard', [
  5657. '$http', 'ngCart', function ($http, ngCart) {
  5658.  
  5659. //debugger;
  5660. var restApiUrl = "/APIConnector/APIConnector.asmx/Send";
  5661.  
  5662. this.checkout = function (settings) {
  5663. var data = ngCart.toObject();
  5664.  
  5665. return $http({
  5666. method: 'POST',
  5667. url: restApiUrl,
  5668. headers: {
  5669. 'Content-Type': 'application/x-www-form-urlencoded'
  5670. },
  5671. data: 'action=cashier/prepare-order&data=' + encodeURIComponent(data)
  5672. });
  5673. //var deffered = $q.defer();
  5674.  
  5675. // $http({
  5676. // method: 'POST',
  5677. // url: restApiUrl,
  5678. // headers: {
  5679. // 'Content-Type': 'application/x-www-form-urlencoded'
  5680. // },
  5681. // data: 'action=cashier/prepare-order&data=' + ngCart.toObject()
  5682. // }).success(function(data) {
  5683.  
  5684. // console.log(data);
  5685.  
  5686.  
  5687. // deffered.resolve(data);
  5688.  
  5689. // }).error(function() {
  5690.  
  5691. // deffered.reject('There was an error');
  5692. // });
  5693.  
  5694. // return deffered.promise;
  5695. }
  5696.  
  5697. }
  5698. ])
  5699. .factory('ngCart.GetCountryByIpService', [
  5700. '$http', '$q', function ($http, $q) {
  5701. var service = {};
  5702.  
  5703. function getFromFreeGeoIp() {
  5704. var deffered = $q.defer();
  5705. $http({
  5706. url: 'https://freegeoip.net/json/',
  5707. timeout: 500
  5708. }).success(function (location) {
  5709. if (location.country_code == null || location.country_code == undefined || location.country_code == 'undefined') {
  5710. return;
  5711. }
  5712. console.log("freegeoip.net success");
  5713. deffered.resolve(location.country_code);
  5714.  
  5715. }).error(function () {
  5716.  
  5717. deffered.reject('There was an error');
  5718. });
  5719.  
  5720. return deffered.promise;
  5721. }
  5722.  
  5723. function getFromIp2c() {
  5724. var deffered = $q.defer();
  5725. $http({
  5726. url: 'http://ip-api.com/json',
  5727. timeout: 500
  5728. }).success(function (location) {
  5729. console.log("ip-api.com success");
  5730. deffered.resolve(location.countryCode);
  5731.  
  5732. }).error(function () {
  5733. deffered.reject('There was an error');
  5734. });
  5735.  
  5736. return deffered.promise;
  5737. }
  5738.  
  5739. function getFromMaxMind() {
  5740. var deffered = $q.defer();
  5741.  
  5742. //debugger;
  5743. deffered.resolve(getCookie("maxMindCountryCode"));
  5744.  
  5745. return deffered.promise;
  5746. }
  5747.  
  5748. service.getCountryCodeByIp = function () {
  5749.  
  5750. var deffered = $q.defer();
  5751. var resultOfFreeSerice = [];
  5752.  
  5753. function toStartPaidService() {
  5754. console.log(resultOfFreeSerice);
  5755. if (resultOfFreeSerice.length === 2) {
  5756. if (resultOfFreeSerice.every(function (value, index, ar) {
  5757. if (value) {
  5758. return false;
  5759. } else {
  5760. return true;
  5761. }
  5762. })) {
  5763. console.log("starting paid service");
  5764.  
  5765. $q.when(getFromMaxMind(), (function (data) {
  5766. console.log(data);
  5767. deffered.resolve(data);
  5768. }));
  5769. } else if (resultOfFreeSerice.length === 2) {
  5770. console.log("fail");
  5771. }
  5772. }
  5773. }
  5774.  
  5775. $q.when(getFromMaxMind(), (function (data) {
  5776. console.log(data);
  5777. deffered.resolve(data);
  5778. }));
  5779.  
  5780. //$q.when(getFromFreeGeoIp(), (function (data) {
  5781. // console.log("freegeoip " + data);
  5782. // deffered.resolve(data);
  5783.  
  5784. //}), function () {
  5785. // console.log("freegeoip failed");
  5786. // resultOfFreeSerice.push(false);
  5787. // toStartPaidService();
  5788. //});
  5789.  
  5790. //$q.when(getFromIp2c(), (function (data) {
  5791. // console.log("ip2c.org " + data);
  5792. // deffered.resolve(data);
  5793.  
  5794. //}), function () {
  5795. // console.log("ip2c failed");
  5796. // resultOfFreeSerice.push(false);
  5797. // toStartPaidService();
  5798. //});
  5799.  
  5800.  
  5801. return deffered.promise;
  5802. }
  5803.  
  5804. return service;
  5805. }
  5806. ])
  5807. .filter('floor', function () {
  5808. return function (input) {
  5809. return Math.floor(input);
  5810. };
  5811. })
  5812. .filter('round', function () {
  5813. return function (input) {
  5814. return Math.round(input);
  5815. };
  5816. })
  5817. .directive('validNumber', function () {
  5818. return {
  5819. require: '?ngModel',
  5820. link: function (scope, element, attrs, ngModelCtrl) {
  5821. if (!ngModelCtrl) {
  5822. return;
  5823. }
  5824.  
  5825. ngModelCtrl.$parsers.push(function (val) {
  5826. if (angular.isUndefined(val)) {
  5827. var val = '';
  5828. }
  5829. var clean = val.replace(/[^0-9]+/g, '');
  5830. if (val !== clean) {
  5831. ngModelCtrl.$setViewValue(clean);
  5832. ngModelCtrl.$render();
  5833. }
  5834. return clean;
  5835. });
  5836.  
  5837. element.bind('keyup keydown', function (event) {
  5838. if (event.keyCode === 32) {
  5839. event.preventDefault();
  5840. }
  5841. });
  5842. }
  5843. };
  5844. })
  5845. .directive('validNumberDecimal', function () {
  5846. return {
  5847. require: '?ngModel',
  5848. link: function (scope, element, attrs, ngModelCtrl) {
  5849. if (!ngModelCtrl) {
  5850. return;
  5851. }
  5852.  
  5853. ngModelCtrl.$parsers.push(function (val) {
  5854. if (angular.isUndefined(val)) {
  5855. var val = '';
  5856. }
  5857. var clean = val.replace(/[^0-9\.]/g, '');
  5858. var decimalCheck = clean.split('.');
  5859.  
  5860. if (!angular.isUndefined(decimalCheck[1])) {
  5861. decimalCheck[1] = decimalCheck[1].slice(0, 2);
  5862. clean = decimalCheck[0] + '.' + decimalCheck[1];
  5863. }
  5864. if (val !== clean) {
  5865. ngModelCtrl.$setViewValue(clean);
  5866. ngModelCtrl.$render();
  5867. }
  5868. return clean;
  5869. });
  5870.  
  5871. element.bind('keyup keydown', function (event) {
  5872. if (event.keyCode === 32) {
  5873. event.preventDefault();
  5874. }
  5875. });
  5876. }
  5877. };
  5878. })
  5879. .filter('translate', [
  5880. '$rootScope', 'ErrorMessages', function ($rootScope, ErrorMessages) {
  5881. return function (items) {
  5882. var filtered = [];
  5883. var currentLangErrorsArr = ErrorMessages[$rootScope.language];
  5884. if (typeof currentLangErrorsArr === 'undefined') {
  5885. currentLangErrorsArr = ErrorMessages["en"];
  5886. }
  5887. if (items !== null && typeof (items) !== "undefined" && items.length > 0) {
  5888.  
  5889. for (var i = 0; i < items.length; i++) {
  5890. var item = items[i];
  5891.  
  5892. if (item.ErrorMessage[item.ErrorMessage.length - 1] === ".")
  5893. item.ErrorMessage = item.ErrorMessage.slice(0, -1);
  5894. var err = currentLangErrorsArr.filter(function (x) {
  5895. if (x.error === item.ErrorMessage) {
  5896. return true;
  5897. } else {
  5898. return false;
  5899. }
  5900. });
  5901. if (err.length > 0) {
  5902. filtered.push(err[0].text);
  5903. } else {
  5904.  
  5905. filtered.push(item.ErrorMessage);
  5906. }
  5907. }
  5908. } else {
  5909. return items;
  5910. }
  5911.  
  5912. return filtered;
  5913. };
  5914. }
  5915. ])
  5916. .directive('onlyAlphabetsAndNumbers', function () {
  5917. return {
  5918. require: '?ngModel',
  5919. link: function (scope, element, attrs, ngModelCtrl) {
  5920. if (!ngModelCtrl) {
  5921. return;
  5922. }
  5923. ngModelCtrl.$parsers.push(function (val) {
  5924. if (angular.isUndefined(val)) {
  5925. var val = '';
  5926. }
  5927. var transformedInput = val.replace(/[^а-яА-ЯёЁa-zA-Z-0-9,.№-\s-]+/, '');
  5928. if (transformedInput !== val) {
  5929. ngModelCtrl.$setViewValue(transformedInput);
  5930. ngModelCtrl.$render();
  5931. }
  5932. return transformedInput;
  5933. });
  5934. }
  5935. };
  5936. })
  5937. .directive('onlyAlphabets', function () {
  5938. return {
  5939. require: '?ngModel',
  5940. link: function (scope, element, attrs, ngModelCtrl) {
  5941. if (!ngModelCtrl) {
  5942. return;
  5943. }
  5944.  
  5945. ngModelCtrl.$parsers.push(function (val) {
  5946. if (angular.isUndefined(val)) {
  5947. var val = '';
  5948. }
  5949. var transformedInput = val.replace(/([^а-яА-ЯёЁ |a-zA-Z-_]+$)/, '');
  5950. if (transformedInput !== val) {
  5951. ngModelCtrl.$setViewValue(transformedInput);
  5952. ngModelCtrl.$render();
  5953. }
  5954. return transformedInput;
  5955. });
  5956. }
  5957. };
  5958. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement