Advertisement
Guest User

Untitled

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