Advertisement
Guest User

Untitled

a guest
Mar 19th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 32.10 KB | None | 0 0
  1.  
  2. kcart = function(){};
  3. kcart.prototype.construct = function(lander)
  4. {
  5. "use strict";
  6. if(typeof lander !== 'object')
  7. {
  8. console.log("1001: Cannot build cart without instance of lander");
  9. return;
  10. }
  11.  
  12. this.lander = lander;
  13. this.validator = lander.validator;
  14. this.defaultProduct = lander.defaultProduct;
  15. this.defaultShipProfile = lander.defaultShipProfile;
  16.  
  17. //init some other objects
  18. this.products = lander.products;
  19. this.orderItems = lander.orderItems;
  20. this.sessionData = {};
  21. this.totalsNodes = {};
  22.  
  23. //profiles
  24. this.profiles = {};
  25. this.profiles.shipping = lander.shipProfiles;
  26. this.profiles.coupon = lander.coupons;
  27. this.profiles.taxes = lander.taxes;
  28.  
  29. this.currency = lander.currencySymbol;
  30.  
  31. this.cartDetail = document.getElementById('kcartDetail');
  32.  
  33. //define any kcartWidget blocks by
  34. this.cartWidgets = [];
  35. var nodes = document.getElementsByClassName("kcartWidget");
  36. for(var i=0;i<nodes.length;i++){
  37. this.cartWidgets.push(nodes[i]);}
  38.  
  39. this.cartTotals = [];
  40. nodes = document.getElementsByClassName("kcartTotals");
  41. for(i=0;i<nodes.length;i++){
  42. this.cartTotals.push(nodes[i]);}
  43.  
  44. this.upgradeCartDetail();
  45. this.upgradeAddToCartButtons();
  46. this.upgradeWidgets();
  47. this.upgradeCartTotals();
  48. this.upgradeExtraCheckoutProducts();
  49.  
  50. };
  51.  
  52. //Utility functions
  53. kcart.prototype.getProfile = function(name)
  54. {
  55. "use strict";
  56. if(this.profiles[name]){
  57. return this.profiles[name];}
  58.  
  59. console.log("getProfile could not find profile with name "+name);
  60. return false;
  61. };
  62.  
  63. kcart.prototype.sendAjaxRequest = function(url,params,callback)
  64. {
  65. "use strict";
  66. return this.lander.sendAjaxRequest(url,params,callback);
  67. };
  68. kcart.prototype.ajaxCallMethod = function(method,params,cb1,cb2)
  69. {
  70. "use strict";
  71. return this.lander.ajaxCallMethod(method,params,cb1,cb2);
  72. };
  73.  
  74.  
  75. /*
  76. displayWidget
  77. -replaces html content of cartWidget div with what is returned from ajax call
  78. */
  79.  
  80. kcart.prototype.displayWidget = function()
  81. {
  82. "use strict";
  83. var widgets = this.widgets;
  84. var success = function(html)
  85. {
  86. console.log(widgets);
  87. for(var i in widgets){
  88. if(widgets[i]){
  89. widgets[i].innerHTML = html;}}
  90. };
  91.  
  92. this.ajaxCallMethod("getWidget",null,success);
  93. };
  94.  
  95. /*
  96. displayCart
  97. -replaces html content of kcart div with what is returned from ajax call
  98. */
  99.  
  100. kcart.prototype.displayCart = function()
  101. {
  102. "use strict";
  103. if(this.cartDetail)
  104. {
  105. var kcart = this;
  106. var success = function(result)
  107. {
  108. this.cartDetail.innerHTML = result.body;
  109. kcart.upgradeCartDetail();
  110. };
  111.  
  112. this.ajaxCallMethod("getShoppingCart",null,success);
  113. //window.setTimeout(function(){kcart.displayCart();},5000);
  114. }
  115. };
  116.  
  117. /*
  118. updateSession
  119. -updates php session with updated lineItems
  120. */
  121.  
  122. kcart.prototype.updateSession = function(items)
  123. {
  124. items = items || this.getOrderItems();
  125. var params = {};
  126. params.cartItems = items;
  127. params.cartItems = JSON.stringify(params.cartItems);
  128. var kcart = this;
  129. this.ajaxCallMethod("updateCart",params,function(){kcart.displayWidget();});
  130. }
  131.  
  132. kcart.prototype.upgradeCartTotals = function()
  133. {
  134. var classes = ['kcartSubTotal','kcartShipTotal','kcartSalesTax','kcartDiscount','kcartInsurance','kcartGrandTotal'];
  135. for(i in classes){
  136. var name = classes[i];
  137. this.totalsNodes[name] = [];
  138. var nodes = document.getElementsByClassName(name);
  139. for(var n=0;n<nodes.length;n++)
  140. this.totalsNodes[name].push(nodes[n]);
  141. }
  142. }
  143.  
  144. kcart.prototype.upgradeCartDetail = function()
  145. {
  146. if(!this.cartDetail)
  147. return;
  148.  
  149. this.upgradeShopButtons();
  150. this.upgradeLineItems();
  151. }
  152.  
  153. kcart.prototype.upgradeLineItems = function()
  154. {
  155. //need mappings by productId for all the UI objects
  156. this.lineItems = {};
  157.  
  158. //get the container div of the shopping cart
  159. var container = this.cartDetail;
  160.  
  161. var nodes = container.getElementsByClassName("kcartItem");
  162.  
  163. var kcart = this;
  164. for(var i=0;i<nodes.length;i++)
  165. {
  166. var node = nodes[i];
  167. var productId = parseInt(node.getAttribute('productId'));
  168.  
  169. //map elements on this line by productId and assign onclick event listeners
  170. this.lineItems[productId] = {};
  171. var item = this.lineItems[productId];
  172. item.productId = productId;
  173. item.parentRow = node;
  174.  
  175. //a useful function for this mini object
  176. this.lineItems[productId].getQty = function(){
  177. return parseInt(this.itemQty.innerHTML);
  178. };
  179.  
  180. //upgrade minus button
  181. item.minusBtn = node.getElementsByClassName('kcartMinusBtn')[0];
  182. if(item.minusBtn)
  183. {
  184. item.minusBtn.lineItem = item;
  185. item.minusBtn.onclick = function(){kcart.minusItem(this.lineItem.productId)};
  186. }
  187. //upgrade plus button
  188. item.plusBtn = node.getElementsByClassName('kcartPlusBtn')[0];
  189. if(item.plusBtn)
  190. {
  191. item.plusBtn.lineItem = item;
  192. item.plusBtn.onclick = function(){kcart.plusItem(this.lineItem.productId)};
  193. }
  194. //upgrade remove button
  195.  
  196. item.removeBtn = node.getElementsByClassName('kcartRemoveBtn')[0];
  197. if(item.removeBtn)
  198. {
  199. item.removeBtn.lineItem = item;
  200. item.removeBtn.onclick = function(){kcart.removeItem(this.lineItem.productId)};
  201. }
  202. //upgrade itemQty span
  203. item.itemQty = node.getElementsByClassName('kcartItemQty')[0];
  204. item.itemQty.lineItem = item;
  205. }
  206.  
  207. //now that everything is upgraded, we can pull the selected order items from the html
  208. this.getOrderItems();
  209.  
  210.  
  211. }
  212.  
  213. kcart.prototype.getOrderItems = function()
  214. {
  215. if(this.lander.pageType == 'checkoutPage')
  216. {
  217.  
  218. this.orderItems = {};
  219. if(this.cartDetail)
  220. {
  221. for(var i in this.lineItems)
  222. {
  223. var item = this.lineItems[i];
  224. this.orderItems[i] = item.getQty();
  225. }
  226. }
  227. else
  228. {
  229.  
  230. var productId = this.getValue('productId');
  231. if(!productId || !this.products[productId])
  232. productId = this.defaultProduct;
  233.  
  234. // console.log(this.lander.selectedProduct);
  235. if(this.lander.selectedProduct)
  236. productId = this.lander.selectedProduct;
  237.  
  238.  
  239. this.orderItems[productId]=1;
  240.  
  241. var nodes = document.getElementsByClassName('kformCheckoutUpsell');
  242. for(var i = 0;i<nodes.length;i++)
  243. {
  244. var node = nodes[i];
  245. productId = node.value;
  246. var qty = node.getAttribute('quantity') || '1';
  247.  
  248. if(!this.lander.products[productId])
  249. console.log("skipping checkout upsell with productId: "+productId+". Product not found. It may be necessary to update config.php.");
  250. else if(node.checked)
  251. this.orderItems[productId] = qty;
  252. }
  253. }
  254. }
  255. return this.orderItems;
  256. }
  257.  
  258. kcart.prototype.minusItem = function(productId)
  259. {
  260. this.getOrderItems();
  261. var items = this.orderItems;
  262. if(items[productId])
  263. {
  264. if(items[productId] > 1)
  265. items[productId]--;
  266.  
  267. if(this.cartDetail)
  268. {
  269. var itemQty = this.lineItems[productId].itemQty;
  270. itemQty.innerHTML = items[productId];
  271. }
  272. }
  273. this.updateSession(items);
  274. this.displayTotals();
  275. }
  276.  
  277. kcart.prototype.plusItem = function(productId)
  278. {
  279. var items = this.getOrderItems();
  280. if(items[productId])
  281. {
  282. items[productId]++;
  283. if(this.cartDetail)
  284. {
  285. var itemQty = this.lineItems[productId].itemQty;
  286. itemQty.innerHTML = items[productId];
  287. }
  288. }
  289. this.updateSession();
  290. this.displayTotals();
  291. }
  292. kcart.prototype.removeItem = function(productId)
  293. {
  294. console.log(productId);
  295. var items = this.getOrderItems();
  296. if(items[productId])
  297. {
  298. if(this.cartDetail)
  299. {
  300. var node = this.lineItems[productId].parentRow;
  301. node.parentNode.removeChild(node);
  302. this.upgradeLineItems();
  303. }
  304. }
  305. this.updateSession();
  306. this.displayTotals();
  307. }
  308. kcart.prototype.upgradeAddToCartButtons = function()
  309. {
  310. var kcart = this;
  311.  
  312. //grab all nodes with matching class name
  313. var nodes = document.getElementsByClassName("kcartAddToCartButton");
  314. for(var i=0;i<nodes.length;i++)
  315. {
  316. var node = nodes[i];
  317.  
  318. //set onclick event listener with the redirect action
  319. node.addEventListener('click',function()
  320. {
  321. var productId = parseInt(this.getAttribute('productId'));
  322. var qty = parseInt(this.getAttribute('quantity'));
  323. kcart.addToCart(productId,qty);
  324. });
  325.  
  326. }
  327. }
  328.  
  329. kcart.prototype.upgradeShopButtons = function()
  330. {
  331. if(!this.cartDetail)
  332. return;
  333.  
  334. //get the container div of the shopping cart
  335. var container = this.cartDetail;
  336.  
  337. //grab all nodes with matching class name
  338. var nodes = container.getElementsByClassName("kcartShopButton");
  339. for(var i=0;i<nodes.length;i++)
  340. {
  341. var node = nodes[i];
  342. //set onclick event listener with the redirect action
  343. node.addEventListener('click',function()
  344. {
  345. var url = this.getAttribute('href');
  346. window.location = url;
  347. });
  348.  
  349. }
  350. }
  351. kcart.prototype.upgradeWidgets = function()
  352. {
  353. this.widgets = [];
  354.  
  355. //grab all nodes with matching class name
  356. var nodes = document.getElementsByClassName("kcartWidget");
  357. for(var i=0;i<nodes.length;i++)
  358. {
  359. var node = nodes[i];
  360. this.widgets.push(node);
  361. }
  362. }
  363.  
  364.  
  365. kcart.prototype.addToCart = function(productId,qty)
  366. {
  367. var originalProductId = productId;
  368. productId = parseInt(productId);
  369. qty = parseInt(qty);
  370.  
  371. if(isNaN(qty))
  372. qty = 1;
  373.  
  374. if(isNaN(productId))
  375. {
  376. console.log("could not add product, invalid productId: "+originalProductId);
  377. return;
  378. }
  379.  
  380. var items = this.getOrderItems();
  381. if(items[productId])
  382. items[productId] += qty;
  383. else
  384. items[productId] = qty;
  385.  
  386. this.updateSession();
  387.  
  388. }
  389.  
  390. kcart.prototype.getValue = function(name)
  391. {
  392. if(this.lander.getValue(name))
  393. return this.lander.getValue(name)
  394. else if(this.lander.validator)
  395. return this.lander.validator.fetchFormValue(name);
  396. else if(this.sessionData[name])
  397. return this.sessionData[name];
  398. return false;
  399. }
  400.  
  401. kcart.prototype.getShipAddress = function()
  402. {
  403. var address1 = this.getValue('shipAddress1') || this.getValue('address1');
  404. var address2 = this.getValue('shipAddress2') || this.getValue('address2');
  405. var city = this.getValue('shipCity') || this.getValue('city');
  406. var state = this.getValue('shipState') || this.getValue('state');
  407. var postalCode = this.getValue('shipPostalCode') || this.getValue('postalCode');
  408. var country = this.getValue('shipCountry') || this.getValue('country');
  409. return {address1:address1,address2:address2,city:city,state:state,postalCode:postalCode,country:country};
  410. }
  411.  
  412. kcart.prototype.getShipProfile = function()
  413. {
  414. var profileId = this.getValue('shipProfileId');
  415. if(!profileId && this.defaultShipProfile)
  416. profileId = this.defaultShipProfile;
  417. if(profileId && this.profiles.shipping[profileId])
  418. return this.profiles.shipping[profileId];
  419. };
  420. kcart.prototype.getTaxRate = function()
  421. {
  422. var shipAddress = this.getShipAddress();
  423. var country = shipAddress.country;
  424. var state = shipAddress.state;
  425.  
  426. var tax_key = country+ '-' + state
  427. if(!this.profiles.taxes[tax_key])
  428. tax_key = country + '-*';
  429.  
  430. return parseFloat(this.profiles.taxes[tax_key]) || 0;
  431. };
  432. //getting cardinal JTW auth for 3DS
  433. kcart.prototype.getCardinalAuth = function(params)
  434. {
  435. var deferred = new $.Deferred();
  436.  
  437.  
  438.  
  439. var lander = this.lander;
  440. lander.setValue('JWTContainer','');
  441. lander.setValue('JWTReturn','');
  442. lander.setValue('CarSteps','');
  443.  
  444. params = params || {};
  445. //params.orderId = lander.getValue('orderId');
  446. params.firstName = lander.getValue('firstName');
  447. params.lastName = lander.getValue('lastName');
  448. var shipAddress = lander.getValue('shipAddress1');
  449. var city = lander.getValue('shipCity');
  450. var postalCode = lander.getValue('shipPostalCode');
  451. var state = lander.getValue('shipState');
  452. var country = lander.getValue('shipCountry');
  453. if (shipAddress)
  454. params.shipAddress1 = shipAddress;
  455. else
  456. params.shipAddress1 = lander.getValue('address1');
  457. if (city)
  458. params.shipCity = city;
  459. else
  460. params.shipCity = lander.getValue('city');
  461. if (state)
  462. params.shipState = state;
  463. else
  464. params.shipState = lander.getValue('state');
  465. if (postalCode)
  466. params.shipPostalCode = postalCode;
  467. else
  468. params.shipPostalCode = lander.getValue('postalCode');
  469. if (country)
  470. params.shipCountry = country;
  471. else
  472. params.shipCountry = lander.getValue('country');
  473. params.method = 'importAuth';
  474. //params.action = 'AUTH';
  475.  
  476.  
  477. if(!params.shipAddress1 || !params.shipCity || !params.shipPostalCode || !params.shipState | !params.firstName)
  478. return;
  479.  
  480. //do not set a redirect
  481. var loc = window.location.toString();
  482. params.errorRedirectsTo = loc.indexOf('?') > -1 ? loc.substr(0,loc.indexOf('?')) : loc;
  483. // we will have to check for upsell page later
  484. if(lander.pageType === 'checkoutPage')
  485. {
  486. params.orderItems = JSON.stringify(this.orderItems);
  487. }
  488.  
  489.  
  490. //lander.isProcessing = true;
  491.  
  492. var success = function(result){
  493. lander.isProcessing = false;
  494. //lander.hideProgressBar();
  495. lander.setValue('JWTContainer',result);
  496. if(params.action === 'AUTH')
  497. {
  498. Cardinal.configure({
  499. logging: {
  500. level: "on"
  501. }
  502. });
  503. Cardinal.setup("init", {
  504. jwt: document.getElementById('JWTContainer').value
  505. });
  506. Cardinal.on('payments.setupComplete', function(){
  507. console.log('setup completed');
  508. });
  509. Cardinal.start("cca", {
  510. OrderDetails: {
  511. OrderNumber: params.orderId,
  512. Amount: '2000',
  513. CurrencyCode: '840'
  514. },
  515. Consumer: {
  516. Account: {
  517. AccountNumber: params.cardNumber,
  518. ExpirationMonth: params.cardMonth,
  519. ExpirationYear: params.cardYear
  520. }
  521.  
  522. }
  523. });
  524. Cardinal.on("payments.validated", function (data, jwt) {
  525. switch(data.ActionCode){
  526. case "SUCCESS":
  527. document.getElementById("JWTReturn").value = jwt;
  528. var step = 'STEP2';
  529. document.getElementById("CarSteps").value = step;
  530. return 'SUCCESS';
  531. break;
  532.  
  533. case "NOACTION":
  534. document.getElementById("JWTReturn").value = jwt;
  535. var step = 'STEP2';
  536. document.getElementById("CarSteps").value = step;
  537. return 'SUCCESS';
  538. break;
  539.  
  540. case "FAILURE":
  541. document.getElementById("JWTReturn").value = jwt;
  542. var step = 'STEP2';
  543. document.getElementById("CarSteps").value = step;
  544. return 'SUCCESS';
  545. break;
  546.  
  547. case "ERROR":
  548. document.getElementById("JWTReturn").value = jwt;
  549. var step = 'STEP2';
  550. document.getElementById("CarSteps").value = step;
  551. return 'SUCCESS';
  552. break;
  553. }
  554. });
  555. //Cardinal.off('payments.validated');
  556. }
  557.  
  558. };
  559. var failure = function(result,code){
  560. lander.isProcessing = false;
  561. lander.hideProgressBar();
  562. kform.validator.triggerError(result);
  563. };
  564. lander.displayProgressBar('Getting 3DS Perms...');
  565. lander.ajaxCallMethod(params.method,params,success,failure);
  566.  
  567. // SIMULATE SOME TIME TO PROCESS FUNCTION
  568. setTimeout(function () {
  569. // This line is what resolves the deferred object
  570. // and it triggers the .done to execute
  571. deferred.resolve('SUCCESS');
  572. }, 15000)
  573. return deferred.promise();
  574.  
  575. };
  576. //getting tax from tax service
  577. kcart.prototype.getExternalTax = function(params)
  578. {
  579. if(this.isProcessing)
  580. {
  581. this.validator.triggerError('paymentProcessing');
  582. return false;
  583. }
  584. if(!this.lander.taxServiceId)
  585. return;
  586.  
  587. var csymbol = this.currencySymbol;
  588. var lander = this.lander;
  589. params = params || {};
  590. params.firstName = lander.getValue('firstName');
  591. params.lastName = lander.getValue('lastName');
  592. var shipAddress = lander.getValue('shipAddress1');
  593. var city = lander.getValue('shipCity');
  594. var postalCode = lander.getValue('shipPostalCode');
  595. var state = lander.getValue('shipState');
  596. var country = lander.getValue('shipCountry');
  597. if (shipAddress)
  598. params.shipAddress1 = shipAddress;
  599. else
  600. params.shipAddress1 = lander.getValue('address1');
  601. if (city)
  602. params.shipCity = city;
  603. else
  604. params.shipCity = lander.getValue('city');
  605. if (state)
  606. params.shipState = state;
  607. else
  608. params.shipState = lander.getValue('state');
  609. if (postalCode)
  610. params.shipPostalCode = postalCode;
  611. else
  612. params.shipPostalCode = lander.getValue('postalCode');
  613. if (country)
  614. params.shipCountry = country;
  615. else
  616. params.shipCountry = lander.getValue('country');
  617. params.method = 'importTax';
  618. params.taxExemption = lander.getValue('taxExemption');
  619.  
  620. if(!params.shipAddress1 || !params.shipCity || !params.shipPostalCode || !params.shipState | !params.firstName)
  621. return;
  622. //do not set a redirect
  623. var loc = window.location.toString();
  624. params.errorRedirectsTo = loc.indexOf('?') > -1 ? loc.substr(0,loc.indexOf('?')) : loc;
  625. // we will have to check for upsell page later
  626. if(lander.pageType === 'checkoutPage')
  627. {
  628. params.orderItems = JSON.stringify(this.orderItems);
  629. }
  630.  
  631. lander.isProcessing = true;
  632.  
  633. var success = function(result){
  634. lander.isProcessing = false;
  635. lander.hideProgressBar();
  636. cart = lander.cart;
  637. cart.grandTotal -= cart.salesTax;
  638. cart.salesTax = parseFloat(result);
  639. cart.grandTotal += cart.salesTax;
  640. for(var cls in cart.totalsNodes)
  641. {
  642. var name = cls.substr(5);
  643. name = name.substr(0,1).toLowerCase()+name.substr(1);
  644. var amount = cart[name];
  645. for(var i in cart.totalsNodes[cls])
  646. {
  647. var node = cart.totalsNodes[cls][i];
  648. node.innerHTML = cart.currency+amount.toFixed(2);
  649. if(name == 'discount' || name == 'insurance')
  650. {
  651. if(node.parentNode.tagName == 'TR')
  652. node.parentNode.style.display = amount > 0 ? 'table-row' : 'none';
  653. }
  654. }
  655. }
  656. };
  657. var failure = function(result,code){
  658. lander.isProcessing = false;
  659. lander.getTax = false;
  660. lander.hideProgressBar();
  661. kform.validator.triggerError(result);
  662. };
  663. lander.displayProgressBar('Calculating sales tax...');
  664. lander.ajaxCallMethod(params.method,params,success,failure);
  665. return false;
  666.  
  667. };
  668. kcart.prototype.getInsurance = function()
  669. {
  670. return this.getValue('insureShipment') ? parseFloat(this.lander.insureShipPrice) : 0;
  671. };
  672. kcart.prototype.getMicroTime = function()
  673. {
  674. return (new Date).getTime() / 1000;
  675. }
  676. kcart.prototype.displayTotals = function()
  677. {
  678. this.calculateTotals();
  679. for(var cls in this.totalsNodes)
  680. {
  681. var name = cls.substr(5);
  682. name = name.substr(0,1).toLowerCase()+name.substr(1);
  683. var amount = this[name];
  684. for(var i in this.totalsNodes[cls])
  685. {
  686. var node = this.totalsNodes[cls][i];
  687. node.innerHTML = this.currency+amount.toFixed(2);
  688. if(name == 'discount' || name == 'insurance')
  689. {
  690. if(node.parentNode.tagName == 'TR')
  691. node.parentNode.style.display = amount > 0 ? 'table-row' : 'none';
  692. }
  693. }
  694. }
  695. }
  696.  
  697. kcart.prototype.calculateTotals = function()
  698. {
  699.  
  700. this.subTotal = 0.00;
  701. this.salesTax = 0.00;
  702. this.shipTotal = 0.00;
  703. this.grandTotal = 0.00;
  704. this.discount = 0.00;
  705. this.insurance = 0.00;
  706.  
  707. //get items currently in cart
  708. var items = this.getOrderItems();
  709.  
  710. //profiles that affect pricing
  711. var products = this.getProducts();
  712. var shipProfile = this.getShipProfile();
  713. var taxRate = this.getTaxRate();
  714. this.insurance = this.getInsurance();
  715.  
  716. //total up price and shipping
  717. for(var i in items)
  718. {
  719. var qty = items[i];
  720. var prod = products[i];
  721. this.subTotal += parseFloat(prod.price) * qty;
  722. this.shipTotal += parseFloat(prod.shipPrice) * qty;
  723. }
  724.  
  725. if(shipProfile)
  726. {
  727. if(shipProfile.applyEntireOrder && shipProfile.matchedShipPrice)
  728. {
  729. if(shipProfile.isUpcharge)
  730. this.shipTotal += parseFloat(shipProfile.matchedShipPrice);
  731. else
  732. this.shipTotal = parseFloat(shipProfile.matchedShipPrice);
  733. }
  734.  
  735. var freeShipThreshold = parseFloat(shipProfile.freeShipThreshold);
  736. if(freeShipThreshold > 0 && this.subTotal >= freeShipThreshold)
  737. this.shipTotal = 0;
  738. }
  739.  
  740.  
  741. var taxable = this.subTotal;
  742. var couponCode = this.getValue('couponCode')? this.getValue('couponCode') : null;
  743. var campaignId = this.campaignId;
  744. var coupons = this.profiles.coupon;
  745. if(couponCode)
  746. var discounts = this.getDiscounts(couponCode,items,coupons);
  747. else
  748. var discounts = false;
  749. var couponsDiv = document.getElementById("orderCoupons");
  750. if(discounts)
  751. {
  752. //apply any coupons
  753.  
  754. //Now we have the discount values. Time to do the math and apply the discounts
  755. var orderPriceTotal = this.subTotal;
  756. var orderShipTotal = this.shipTotal;
  757. var discountPrice = 0;
  758.  
  759. //always apply product-level coupons first
  760. for(var campaignProductId in discounts.productDiscounts)
  761. {
  762. var disc = discounts.productDiscounts[campaignProductId];
  763. var inCart = items[campaignProductId];
  764. var itm = products[campaignProductId];
  765. if(inCart)
  766. {
  767. var basePrice = parseFloat(itm.price);
  768. var baseShipping = parseFloat(itm.shipPrice);
  769.  
  770. //first apply the flat discounts
  771. var priceDisc = basePrice <= disc.priceFlat ? basePrice : disc.priceFlat;
  772. var shipDisc = baseShipping <= disc.shipFlat ? baseShipping : disc.shipFlat;
  773.  
  774. //now apply the percent discounts
  775. priceDisc += disc.pricePerc * (basePrice - priceDisc);
  776. shipDisc += disc.shipPerc * (baseShipping - shipDisc);
  777.  
  778. //re-assign the item's discount values
  779. this.discount += shipDisc + priceDisc;
  780.  
  781. //Reduce taxable by price discount
  782. taxable -= priceDisc;
  783.  
  784. //add to order totals to use with coupons that apply discounts to the entire order
  785. orderPriceTotal -= priceDisc;
  786. orderShipTotal -= shipDisc;
  787. }
  788. }
  789.  
  790. //now calculate the total order discounts
  791. disc = discounts.orderDiscounts;
  792.  
  793. //first apply the flat discounts
  794. priceDisc = orderPriceTotal <= disc.priceFlat ? 0 : disc.priceFlat;
  795. shipDisc = orderShipTotal <= disc.shipFlat ? 0 : disc.shipFlat;
  796.  
  797. //now apply the percent discounts
  798. priceDisc += disc.pricePerc * (orderPriceTotal - priceDisc);
  799. shipDisc += disc.shipPerc * (orderShipTotal - shipDisc);
  800.  
  801. this.discount += priceDisc + shipDisc;
  802.  
  803. //Reduce taxable by price discount
  804. taxable -= priceDisc;
  805. if(couponsDiv){
  806. couponsDiv.innerHTML = discounts.coupMessage;
  807. couponsDiv.style.display = "block";
  808. }
  809. this.lander.setValue('couponCode',discounts.couponCode);
  810. }
  811. else
  812. {
  813. if(couponsDiv)
  814. couponsDiv.innerHTML = '';
  815.  
  816. this.lander.setValue('couponCode','');
  817. }
  818.  
  819. //apply tax (s&h is not taxed)
  820. if(this.lander.autoTax)
  821. this.getExternalTax();
  822. else
  823. this.salesTax = taxRate * taxable;
  824. //sum grand total
  825. this.grandTotal = this.subTotal + this.shipTotal + this.salesTax - this.discount + this.insurance;
  826.  
  827. //set the amount for PAAY 3DS if it exists - the amount must be an integer, so rounding up to the nearest whole number
  828. var paayAmount = document.getElementById('paayAmount');
  829. if(paayAmount)
  830. paayAmount.value = Math.ceil(this.grandTotal);
  831. }
  832. return {subTotal:this.subTotal,shipTotal:this.shipTotal,salesTax:this.salesTax,discount:this.discount,insurance:this.insurance};
  833. };
  834.  
  835.  
  836. kcart.prototype.getDiscounts = function(couponCode,items,coupons)
  837. {
  838. var ret = {couponCode:[],
  839. orderDiscounts:{priceFlat:0,pricePerc:0,shipFlat:0,shipPerc:0},
  840. productDiscounts:{},
  841. coupons:[],
  842. coupMessage:''
  843. };
  844.  
  845. var cCodes = couponCode.trim().toUpperCase().split(',');
  846.  
  847. var couponCount = 0;
  848. var obj,flatDiscount,percDiscount;
  849. for(var i in cCodes)
  850. {
  851. var code = cCodes[i];
  852. if(!coupons[code])
  853. continue;
  854.  
  855. coupon = coupons[code];
  856. flatDiscount = coupon.couponDiscountPrice === null ? 0 : parseFloat(coupon.couponDiscountPrice);
  857. percDiscount = coupon.couponDiscountPerc === null ? 0 : parseFloat(coupon.couponDiscountPerc);
  858. if(coupon.couponMax && couponCount >= coupon.couponMax)
  859. break;
  860.  
  861. if(!coupon.campaignProductId)
  862. {
  863. obj = ret.orderDiscounts;
  864. }
  865. else
  866. {
  867. if(!items[coupon.campaignProductId])
  868. {
  869. continue;
  870. }
  871. if(!ret.productDiscounts[coupon.campaignProductId])
  872. ret.productDiscounts[coupon.campaignProductId] = {priceFlat:0,pricePerc:0,shipFlat:0,shipPerc:0};
  873. obj = ret.productDiscounts[coupon.campaignProductId];
  874. }
  875.  
  876. ret.coupMessage += "<span style='color:green;font-weight:bold;'>" + code + "</span> ";
  877.  
  878. isPerc = percDiscount > flatDiscount;
  879. var discount = flatDiscount + percDiscount;
  880.  
  881. if(isPerc)
  882. discount = (parseFloat(discount) * 100).toString() + '%';
  883. var products = this.getProducts();
  884. if(coupon.campaignProductId)
  885. var coupProd = products[coupon.campaignProductId].name;
  886.  
  887. ret.coupMessage += discount + " off "+(coupon.applyTo == 'SHIPPING' ? 'shipping ' : '')+"on "+(coupon.campaignProductId ? coupProd : "Order") +"<br>";
  888.  
  889. if(coupon.applyTo == 'BASE_PRICE')
  890. {
  891. obj.priceFlat += flatDiscount;
  892. obj.pricePerc += percDiscount;
  893. }
  894. else
  895. {
  896. obj.shipFlat += flatDiscount;
  897. obj.shipPerc += percDiscount;
  898. }
  899.  
  900. //ensure percents do not add up more than 100
  901. if(obj.pricePerc > 100)
  902. obj.pricePerc = 100;
  903. if(obj.shipPerc > 100)
  904. obj.shipPerc = 100;
  905.  
  906.  
  907. ret.coupons.push(coupon);
  908. ret.couponCode.push(code);
  909. couponCount++;
  910. }
  911. if(couponCount == 0)
  912. return false;
  913. ret.couponCode = ret.couponCode.join();
  914. return ret;
  915. }
  916.  
  917.  
  918. //gets product pricing with ship profile calculations
  919. //ship profiles have a lot of configurations so there's a bunch of logic to check here
  920. kcart.prototype.getProducts = function()
  921. {
  922. this.profileShipPrice = 0;
  923.  
  924. var products = JSON.parse(JSON.stringify(this.products));
  925. var profile = this.getShipProfile();
  926.  
  927. if(!profile)
  928. return products;
  929.  
  930. profile.matchedShipPrice = null;
  931.  
  932. var shipAddress = this.getShipAddress();
  933. var shipCountry = shipAddress.country;
  934. var shipState = shipAddress.state;
  935. var shipContinent = this.lander.config.continents[shipCountry];
  936.  
  937. if(profile.applyEntireOrder){
  938. var matchRule = null;
  939. var maxRStrength = 0;
  940. var rStrength;
  941.  
  942. for(var i in profile.rules){
  943. rStrength = 0;
  944. var rule = profile.rules[i];
  945. if(rule.region){
  946. if(rule.region.substr(0,4) == 'REG_'){
  947. if(rule.region.substr(4,2) != shipContinent)
  948. continue;
  949. rStrength = 1;
  950. }else{
  951. if(rule.region == shipCountry){
  952. rStrength = 2;
  953. if(rule.state){
  954. if(rule.state == shipState)
  955. rStrength = 3;
  956. else
  957. continue;
  958. }
  959. }else
  960. continue;
  961. }
  962. }
  963. if(rStrength >= maxRStrength){
  964. maxRStrength = rStrength;
  965. matchRule = rule;
  966. }
  967. else
  968. continue;
  969.  
  970. }
  971. if(matchRule)
  972. profile.matchedShipPrice = matchRule.shipPrice;
  973. }else{
  974. for(var i in products){
  975. var prod = products[i];
  976. var productId = prod.productId;
  977.  
  978. var matchRule = null;
  979. var maxPStrength = 0;
  980. var maxRStrength = 0;
  981. for(var i in profile.rules){
  982. var rule = profile.rules[i];
  983. var pStrength = 0;
  984. var rStrength = 0;
  985. if(rule.region){
  986. if(rule.region.substr(0,4) == 'REG_'){
  987. if(rule.region.substr(4,2) != shipContinent)
  988. continue;
  989. rStrength = 1;
  990. }else{
  991. if(rule.region == shipCountry){
  992. rStrength = 2;
  993. if(rule.state)
  994. {
  995. if(rule.state == shipState)
  996. rStrength = 3;
  997. else
  998. continue;
  999. }
  1000. }else
  1001. continue;
  1002. }
  1003. }
  1004. if(rStrength >= maxRStrength)
  1005. maxRStrength = rStrength;
  1006. else
  1007. continue;
  1008. if(rule.productTypeSelect == 'SINGLE' && productId == rule.campaignProductId)
  1009. pStrength = 5;
  1010. else if(rule.productTypeSelect == 'CATEGORY' && prod.productCategoryId == rule.productCategoryId)
  1011. pStrength = 4;
  1012. else if(rule.productTypeSelect == 'OFFERS' && prod.productType == 'OFFER')
  1013. pStrength = 3;
  1014. else if(rule.productTypeSelect == 'UPSELLS' && prod.productType == 'UPSALE')
  1015. pStrength = 2;
  1016. else if(rule.productTypeSelect == 'PRODUCTS')
  1017. pStrength = 1;
  1018.  
  1019. if(pStrength >= maxPStrength){
  1020. matchRule = rule;
  1021. maxPStrength = pStrength;
  1022. }
  1023. }
  1024. var shipPrice = parseFloat(products[productId].shipPrice);
  1025. if(matchRule){
  1026. var profileShipPrice = parseFloat(matchRule.shipPrice);
  1027. if(profile.isUpcharge)
  1028. shipPrice += profileShipPrice;
  1029. else
  1030. shipPrice = profileShipPrice;
  1031. prod.shipPrice = shipPrice;
  1032. }
  1033. }
  1034. }
  1035.  
  1036. //shipProfiles that only bill the highest ship price item
  1037. if(profile.highestShipPriceOnly){
  1038. var maxShipPrid = null;
  1039. var maxShipPrice = 0;
  1040. for(var i in products){
  1041. var prod = products[i];
  1042. var shipPrice = parseFloat(prod.shipPrice);
  1043. if(shipPrice > maxShipPrice){
  1044. maxShipPrid = i;
  1045. maxShipPrice = shipPrice;
  1046. }
  1047. }
  1048. for(var i in products){
  1049. if(i != maxShipPrid)
  1050. products[i].shipPrice = 0;
  1051. }
  1052. }
  1053.  
  1054.  
  1055. return products;
  1056. }
  1057.  
  1058. //for multi-product landers -- selects a product
  1059. kcart.prototype.selectProduct = function(productId)
  1060. {
  1061. if(kform.selectedProduct)
  1062. {
  1063. var curVal = kform.selectedProduct;
  1064. if(curVal == productId)
  1065. return;
  1066. if(kform.productSelectNodes)
  1067. {
  1068. var node = kform.productSelectNodes[curVal];
  1069. if(node)
  1070. {
  1071. node.className = node.className.replace(/kform_selectedProduct/,"");
  1072. node.parentBox.className = node.parentBox.className.replace(/kform_selectedProduct/,"");
  1073. }
  1074. }
  1075. }
  1076.  
  1077. if(kform.productSelectNodes)
  1078. {
  1079. var node;
  1080. if(node = kform.productSelectNodes[productId])
  1081. {
  1082.  
  1083. kform.selectedProduct = productId;
  1084. node.className += " kform_selectedProduct";
  1085. node.parentBox.className += " kform_selectedProduct";
  1086.  
  1087. }
  1088. }
  1089. kform.storeValue('selectedProduct',productId);
  1090.  
  1091. if(typeof kform_userSelectProduct == 'function')
  1092. kform_userSelectProduct(productId);
  1093.  
  1094. this.displayTotals();
  1095. };
  1096.  
  1097.  
  1098. //used by multi-product landers
  1099. kcart.prototype.upgradeProductSelector = function()
  1100. {
  1101. var nodes = document.getElementsByClassName('kform_productSelect');
  1102. var len = nodes.length;
  1103.  
  1104. if(len == 0)
  1105. return;
  1106.  
  1107. this.productSelectNodes = {};
  1108. var defaultProductIsOption = false;
  1109. for(var i = 0;i<len;i++)
  1110. {
  1111. var node = nodes[i];
  1112.  
  1113. var productId = node.getAttribute('productId');
  1114. if(!productId)
  1115. alert("kformError: productSelect button must have the productId attribute");
  1116. node.productId = productId;
  1117.  
  1118. var parent = node;
  1119. var foundParent = false;
  1120. while(parent = parent.parentNode)
  1121. {
  1122. if(typeof parent != 'object')
  1123. break;
  1124.  
  1125. if(typeof parent.className == 'undefined')
  1126. continue;
  1127.  
  1128. if(parent.className.indexOf("kform_productBox") > -1)
  1129. {
  1130. node.parentBox = parent;
  1131. foundParent = true;
  1132. }
  1133. }
  1134.  
  1135. if(!foundParent)
  1136. alert("kformError: productSelect button must be a child of an element with the kform_productBox className");
  1137.  
  1138. this.productSelectNodes[productId] = node;
  1139.  
  1140. if(!this.products[productId])
  1141. alert("kformError: productSelect button has a productId value of "+productId+" but that productId does not exist in this campaign");
  1142.  
  1143.  
  1144. if(!this.hasInput('productSelector'))
  1145. {
  1146. var input = document.createElement('input');
  1147. input.type = 'hidden';
  1148. input.name = 'productSelector';
  1149. this.node.appendChild(input);
  1150. this.inputs['productSelector'] = input;
  1151. }
  1152.  
  1153.  
  1154. if(productId == this.defaultProduct)
  1155. defaultProductIsOption = true;
  1156.  
  1157. node.addEventListener('click',function()
  1158. {
  1159. kform.selectProduct(this.productId);
  1160. });
  1161. }
  1162.  
  1163. if(!defaultProductIsOption)
  1164. alert("kformError: default productId is "+this.defaultProduct+" but this option does not exist in the productSelector");
  1165.  
  1166. var curProd = this.fetchValue('selectedProduct');
  1167. if(!curProd)
  1168. curProd = this.defaultProduct;
  1169.  
  1170. this.selectProduct(curProd);
  1171.  
  1172. };
  1173.  
  1174. //upgrades checkboxes used for additional upsells
  1175. kcart.prototype.upgradeExtraCheckoutProducts = function()
  1176. {
  1177. var nodes = document.getElementsByClassName('kformCheckoutUpsell');
  1178. var len = nodes.length;
  1179.  
  1180. if(len == 0)
  1181. return;
  1182.  
  1183. var cart = this;
  1184.  
  1185. for(var i = 0;i<len;i++)
  1186. {
  1187. var node = nodes[i];
  1188. if(node.type == 'checkbox')
  1189. {
  1190. var upsellId = node.value;
  1191. if(!this.products[upsellId])
  1192. alert("kformError: upsell checkbox has an value of "+upsellId+" but that productId does not exist in this campaign");
  1193.  
  1194. node.addEventListener('click',function(){cart.displayTotals()});
  1195. }
  1196. }
  1197. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement