Advertisement
Guest User

Configurator

a guest
Oct 26th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2.  * Authors: Baptiste DULAC, Thomas CACQUEVELLE
  3.  * (c) Add+ Design
  4.  */
  5.  
  6. // -----------------------------------------------------------------------
  7. // Defines
  8. // -----------------------------------------------------------------------
  9.  
  10. var $viewGrid   = $('.view_grid');
  11. var $moveGrid   = $('.move_grid');
  12. var $grid       = $('#grid');
  13.  
  14. var equivalences = {'1515' : 1, '3030' : 2};
  15.  
  16. // Grid Size
  17. var GRID_SIZE     = 2400 > $viewGrid.width() ? 2400 : $viewGrid.width();
  18. var SQUARE_LIMIT  = 30;
  19. var SQUARE_SIZE   = GRID_SIZE / SQUARE_LIMIT;
  20. var VIEW_HEIGHT   = $viewGrid.height();
  21. var VIEW_WIDTH    = $viewGrid.width();
  22. var MOVE_HEIGHT = (GRID_SIZE * 2) - VIEW_HEIGHT;
  23. var MOVE_WIDTH  = (GRID_SIZE * 2) - VIEW_WIDTH;
  24.  
  25. // Buttons
  26. var $remove_all  = $('#remove_all');
  27. var $saveGrid    = $('#save_grid');
  28. var $downloadLink = $('#download-link');
  29. var $loginModalButton = $('#login-modal-button');
  30. var $registerModalButton = $('#register-modal-button');
  31. var $saveGridButton = $('#save-grid-button');
  32. var $shareGrid = $('#share');
  33. var $shareGridButton = $('#share-grid-button');
  34. var $noCapsOrderButton = $('#no-caps-order-button');
  35. var $withCapsOrderButton = $('#with-caps-order-button');
  36. var $gridItemPopupColorContainer = $('#grid-item-popup-color-container');
  37.  
  38. var $li_item= $('.list_item');
  39. var $li_item_href= $('.list_item a');
  40.  
  41. // Display modules iterator
  42. var onLine = 0;
  43. var id = 0;
  44.  
  45. var currentIndexColors = 0;
  46.  
  47. var backup = {
  48.     x: 0,
  49.     y: 0,
  50.     ref: null,
  51.     rotate: 0,
  52.     base: null
  53. };
  54.  
  55. var ghost = {
  56.     x : 0,
  57.     y : 0,
  58.     item: null
  59. };
  60.  
  61. var loader_module = {};
  62.  
  63. var current_save = {
  64.     id : null,
  65.     name : null
  66. };
  67.  
  68. var see_url_save_delete = {
  69.     hasObject : false
  70. };
  71.  
  72. var isHoverBin   = false;
  73. var grid                = [];
  74. var product             = {};
  75. var sortModulesBySize   = {};
  76.  
  77. var colors = ['whitm','blacm','greym','sandm','navym','olivm','browm','watem','yelom','raspm','turqm','redfm'];
  78.  
  79. var arrayColor = {
  80.     'whitm': '#ECECEC',
  81.     'blacm': '#424242',
  82.     'greym': '#A9A9A9',
  83.     'sandm': '#C6C1AC',
  84.     'navym': '#32627E',
  85.     'olivm': '#7A8975',
  86.     'browm': '#4D3D36',
  87.     'watem': '#B7D7B2',
  88.     'yelom': '#E2C83F',
  89.     'raspm': '#B03244',
  90.     'turqm': '#428891',
  91.     'redfm': '#FF352A'
  92. };
  93.  
  94. var arrayColorName = {
  95.     blacm: 'Nuit',
  96.     browm: 'Chocolat',
  97.     greym: 'Anthracite',
  98.     navym: 'Marine',
  99.     olivm: 'Olive',
  100.     raspm: 'Framboise',
  101.     redfm: 'Orange pop',
  102.     sandm: 'Silex',
  103.     turqm: 'Azur',
  104.     watem: 'Aqua',
  105.     whitm: 'Neige',
  106.     yelom: 'Capucine'
  107. };
  108.  
  109. // -----------------------------------------------------------------------
  110. // Functions
  111. // -----------------------------------------------------------------------
  112.  
  113. function orderButtonClicked(e)
  114. {
  115.     e.preventDefault();
  116.     showModal('#order-modal');
  117. }
  118.  
  119. function orderComposition(hasCaps)
  120. {
  121.     addLoader($('#order-modal-caps-choice'));
  122.     saveGrid(current_save.name, hasCaps, false, function(data) {
  123.         window.location = ORDER_URL + '?productId=' + data.publicId;
  124.     });
  125. }
  126.  
  127. function displayGhost()
  128. {
  129.     $('#ghost').remove();
  130.     var $ghost = $('<div id="ghost"></div>');
  131.     $ghost.css({
  132.         'width' : SQUARE_SIZE * ghost.item.base,
  133.         'height' : SQUARE_SIZE * ghost.item.base,
  134.         'position' : 'absolute',
  135.         'border': '1px dashed #AAA',
  136.         'left' : toPosition(ghost.x),
  137.         'top' : toPosition(ghost.y)
  138.     });
  139.     $grid.append($ghost);
  140. }
  141.  
  142. /**
  143.  * @param item
  144.  * @param code
  145.  * @param rotate
  146.  * @param x
  147.  * @param y
  148.  */
  149. function addItemToGrid(item, code, rotate, x, y)
  150. {
  151.     if (!grid.hasOwnProperty(x))
  152.         grid[x] = [];
  153.  
  154.     grid[x][y] = createItem(code, item.base, rotate, false);
  155.  
  156.     // Module 3030
  157.     if (item.base == 2)
  158.     {
  159.         if (!grid.hasOwnProperty(x + 1))
  160.             grid[x + 1] = [];
  161.  
  162.         grid[x +1 ][y] = createItem(code, item.base, rotate, true);
  163.         grid[x][y + 1] = createItem(code, item.base, rotate, true);
  164.         grid[x + 1][y + 1] = createItem(code, item.base, rotate, true);
  165.     }
  166.     Draw();
  167. }
  168.  
  169. /**
  170.  * @param code
  171.  * @param base
  172.  * @param orientation
  173.  * @param virtual
  174.  * @returns {{code: *, base: *, orientation: *, isVirtual: *}}
  175.  */
  176. function createItem(code, base, orientation, virtual) {
  177.     return {code : code, base: base, orientation: orientation, isVirtual: virtual};
  178. }
  179.  
  180. /**
  181.  * @param pos
  182.  * @returns {number}
  183.  */
  184. function toGrid(pos) {
  185.     if (pos > (GRID_SIZE - SQUARE_SIZE))
  186.         pos = GRID_SIZE - SQUARE_SIZE;
  187.  
  188.     return Math.floor(pos / SQUARE_SIZE) + 1;
  189. }
  190.  
  191. function DisplayMenuAction(){
  192.     $li_item.removeClass('disabled');
  193.     $li_item_href.css({'color':'#000'});
  194. }
  195.  
  196. /**
  197.  * @param c
  198.  * @returns {number}
  199.  */
  200. function toPosition(c)
  201. {
  202.     return (c - 1) * SQUARE_SIZE;
  203. }
  204.  
  205. function removeModule_all()
  206. {
  207.     grid = [];
  208.     $grid.empty();
  209.     DisableMenuAction();
  210.     getCompositionPrice(grid);
  211.     Draw();
  212. }
  213.  
  214.  
  215. function DisableMenuAction()
  216. {
  217.     $li_item_href.css({'color':'grey'});
  218.     $li_item.addClass('disabled');
  219. }
  220.  
  221. /**
  222.  * @param objX
  223.  * @param objY
  224.  * @returns {boolean|*}
  225.  */
  226. function itemExistsInGrid(objX, objY)
  227. {
  228.     return grid.hasOwnProperty(objX) && grid[objX].hasOwnProperty(objY) && grid[objX][objY] != null;
  229. }
  230.  
  231. /**
  232.  * @param item
  233.  * @param x
  234.  * @param y
  235.  * @returns {boolean}
  236.  */
  237. function canDropModule(item, x, y)
  238. {
  239.     if (item.base == 2) {
  240.         return !itemExistsInGrid(x, y) && !itemExistsInGrid(x + 1, y) && !itemExistsInGrid(x ,y + 1) && !itemExistsInGrid(x + 1, y + 1);
  241.     }
  242.     return !itemExistsInGrid(x, y);
  243. }
  244.  
  245. /**
  246.  * @param ref
  247.  * @param srcX
  248.  * @param srcY
  249.  * @param destX
  250.  * @param destY
  251.  * @param rotate
  252.  * @constructor
  253.  */
  254. function moveItemInGrid(ref, srcX, srcY, destX, destY, rotate)
  255. {
  256.  
  257.     //if (!product.hasOwnProperty(ref))
  258.     //    return;
  259.  
  260.     var item = product[ref];
  261.  
  262.     if (!canDropModule(item, destX, destY))
  263.         addItemToGrid(item, item.code, rotate, srcX, srcY);
  264.     else
  265.         addItemToGrid(item, item.code, rotate, destX, destY);
  266. }
  267.  
  268. /**
  269.  * @param srcX
  270.  * @param srcY
  271.  * @constructor
  272.  */
  273. function deleteModule(srcX, srcY)
  274. {
  275.     var item = grid[srcX][srcY];
  276.     if (item.base == 2)
  277.     {
  278.         if (!grid.hasOwnProperty(srcX + 1))
  279.             grid[srcX + 1] = [];
  280.         grid[srcX + 1][srcY] = null;
  281.         grid[srcX][srcY + 1] = null;
  282.         grid[srcX + 1][srcY + 1] = null;
  283.     }
  284.     grid[srcX][srcY] = null;
  285. }
  286.  
  287. /**
  288.  * @param ev
  289.  * @param callback
  290.  */
  291. function handleMouseClick(ev, callback)
  292. {
  293.     var tPos = $('#grid').offset();
  294.     var view_offset = $('.view_grid').offset();
  295.     var mouse_offset = {posX: ev.pageX, posY: ev.pageY};
  296.     var mouse = {posX: ev.pageX, posY: ev.pageY};
  297.     mouse_offset.posX -= view_offset.left;
  298.     mouse_offset.posY -= view_offset.top;
  299.     mouse.posX -= tPos.left;
  300.     mouse.posY -= tPos.top;
  301.     callback(toGrid(mouse.posX), toGrid(mouse.posY), mouse_offset.posX, mouse_offset.posY);
  302. }
  303.  
  304. function hoverTrash()
  305. {
  306.     $(".trash").hover(function() {
  307.             $('.trash').addClass('trash-active');
  308.         }, function() {
  309.             $('.trash').removeClass('trash-active');
  310.         }
  311.     );
  312. }
  313.  
  314. function removeModuleInGrid(x, y)
  315. {
  316.     var $module = getModuleInGrid(x, y);
  317.     $module.remove();
  318. }
  319.  
  320. /**
  321.  * @param x
  322.  * @param y
  323.  * @returns {*|jQuery|HTMLElement}
  324.  */
  325. function getModuleInGrid(x, y)
  326. {
  327.     return $('.grid-item[data-x="' + x + '"][data-y="' + y + '"]');
  328. }
  329.  
  330. /**
  331.  * @param x
  332.  * @param y
  333.  * @returns {boolean}
  334.  */
  335. function moduleIsPresent(x, y)
  336. {
  337.     return getModuleInGrid(x, y).length > 0;
  338. }
  339.  
  340. /**
  341.  * @param x
  342.  * @param y
  343.  * @param inverse
  344.  */
  345. function rotateModuleInGrid(x, y, inverse)
  346. {
  347.     var gridItem = grid[x][y];
  348.     var $module = getModuleInGrid(x, y);
  349.     var oldRotate = gridItem.orientation;
  350.     var rotate = 0;
  351.  
  352.     if (inverse == true)
  353.         rotate = oldRotate - 90 < 0 ? 270 : oldRotate - 90;
  354.     else
  355.         rotate = oldRotate + 90 > 270 ? 0 : oldRotate + 90;
  356.  
  357.     // Save to front
  358.     $module.removeClass('rotate-' + oldRotate).addClass('rotate-' + rotate);
  359.     $module.data('rotate', rotate);
  360.     grid[x][y].orientation = rotate;
  361. }
  362.  
  363. /**
  364.  * @param ref
  365.  * @param x
  366.  * @param y
  367.  * @param rotate
  368.  * @constructor
  369.  */
  370. function addModule(ref, x, y, rotate)
  371. {
  372.  
  373.     if (!product.hasOwnProperty(ref))
  374.         return;
  375.  
  376.     var item = product[ref];
  377.  
  378.     DisplayMenuAction();
  379.  
  380.     var $div = $('<div class="grid-item"></div>');
  381.     $div.attr('data-x', x);
  382.     $div.attr('data-y', y);
  383.     $div.attr('data-ref', ref);
  384.     $div.attr('data-rotate', rotate);
  385.     $div.addClass('rotate-' + rotate);
  386.     $div.css({
  387.         'width': SQUARE_SIZE * item.base,
  388.         'height': SQUARE_SIZE * item.base,
  389.         'background': 'url("' + item.imageConfigurator +'")',
  390.         'top': toPosition(y),
  391.         'left': toPosition(x)
  392.     });
  393.  
  394.     $('#grid').append($div);
  395.  
  396.     $('.grid-item').draggable({
  397.         cursorAt: {top:  20, left: 20},
  398.         start: function(event, ui)
  399.         {
  400.             // Remove tooltips
  401.             $('.grid-item-popup-container.active').remove();
  402.  
  403.             // Create backup module
  404.             backup.x = parseInt($(this).data('x'));
  405.             backup.y = parseInt($(this).data('y'));
  406.             backup.ref = $(this).data('ref');
  407.             backup.rotate = parseInt($(this).data('rotate'));
  408.             backup.binned = false;
  409.  
  410.             var item = product[backup.ref];
  411.             ghost.item = item;
  412.  
  413.             // A bit of css for current drag item
  414.             $(this).css({
  415.                 'opacity' : 0.5,
  416.                 'z-index': 115
  417.             });
  418.  
  419.             ui.helper.css({
  420.                 'width': SQUARE_SIZE * item.base,
  421.                 'height': SQUARE_SIZE * item.base
  422.             });
  423.             deleteModule(backup.x, backup.y);
  424.         },
  425.         drag: function(ev)
  426.         {
  427.             hoverTrash();
  428.             handleMouseClick(ev, function(x, y) {
  429.                 ghost.x = x;
  430.                 ghost.y = y;
  431.                 $('#ghost').remove();
  432.                 if (canDropModule(ghost.item, x, y))
  433.                     displayGhost();
  434.             });
  435.         },
  436.         stop: function(ev)
  437.         {
  438.             $(this).remove();
  439.             $('#ghost').remove();
  440.             if (!isHoverBin)
  441.                 handleMouseClick(ev, function(x, y, mouseX, mouseY)
  442.                 {
  443.                     if (mouseX > 0 && mouseX < VIEW_WIDTH && mouseY > 0 && mouseY < VIEW_HEIGHT)
  444.                     {
  445.                         moveItemInGrid(backup.ref, backup.x, backup.y, x, y, backup.rotate);
  446.                     }
  447.                     else if (product.hasOwnProperty(backup.ref))
  448.                     {
  449.                         addItemToGrid(product[backup.ref], backup.ref, backup.rotate, backup.x, backup.y);
  450.                     }
  451.                 });
  452.             else
  453.                 Draw();
  454.             getCompositionPrice();
  455.         }
  456.     });
  457. }
  458.  
  459. /**
  460.  * @param GRID_SIZE
  461.  * @param VIEW_WIDTH
  462.  * @param VIEW_HEIGHT
  463.  * @param MOVE_WIDTH
  464.  * @param MOVE_HEIGHT
  465.  */
  466. function createGrid(GRID_SIZE,VIEW_WIDTH, VIEW_HEIGHT, MOVE_WIDTH, MOVE_HEIGHT)
  467. {
  468.     $grid.css({
  469.         'position': 'absolute',
  470.         'width' : GRID_SIZE,
  471.         'height' : GRID_SIZE,
  472.         'top': (MOVE_HEIGHT - GRID_SIZE) / 2,
  473.         'left': (MOVE_WIDTH - GRID_SIZE) / 2,
  474.         'background-color': '#ffffff',
  475.         'cursor':'move'
  476.     });
  477.     $viewGrid.css({
  478.         'width' : VIEW_WIDTH,
  479.         'height' : VIEW_HEIGHT,
  480.         'border' : '1px solid #D4D4D5'
  481.     });
  482.     $moveGrid.css({
  483.         position: 'relative',
  484.         top : - (MOVE_HEIGHT - VIEW_HEIGHT) / 2,
  485.         left :  - (MOVE_WIDTH - VIEW_WIDTH) / 2,
  486.         'width' : MOVE_WIDTH,
  487.         'height' : MOVE_HEIGHT,
  488.         'background' : 'blue'
  489.     });
  490. }
  491.  
  492. function hideLoaderGrid()
  493. {
  494.     $('#grid-load').removeClass('ui active inverted dimmer').css({'opacity':1}); // Hide loader grid
  495.     $('#grid-load-text').remove(); // Hide loader grid
  496. }
  497.  
  498. function checkDataLoad()
  499. {
  500.     var data = $('.module-line').data('load');
  501.     if(data == false)
  502.         $('.module-line').attr('data-load', 'true').removeClass('ui loader active');
  503. }
  504.  
  505. /**
  506.  * @param $line
  507.  * @param item
  508.  * @param orientation
  509.  */
  510. function newImage(item, orientation)
  511. {
  512.     return $('<img class="dragme lazy rotate-' + orientation + ' size-' + item.size + '">')
  513.         .attr('data-code', item.code)
  514.         .attr('data-src', item.imageConfigurator)
  515.         .attr('data-rotate', orientation)
  516.         .attr('data-content', item.name)
  517.         .attr('data-variation', 'tiny')
  518.         .attr('data-position', 'top center')
  519.         ;
  520. }
  521.  
  522. function loadImages(color)
  523. {
  524.     var $groupColor = $('.group-color[data-color="' + color + '"]');
  525.     var loaded = $groupColor.data('loaded');
  526.  
  527.     if (!loaded)
  528.     {
  529.         $groupColor.data('loaded', true);
  530.         var $lazyLoadImages = $groupColor.find('img.lazy');
  531.         $lazyLoadImages.lazy({
  532.             bind: "event",
  533.             delay: 0,
  534.             skip_invisible: false,
  535.             onFinishedAll: function() {
  536.                 $groupColor.find('.active.inverted.dimmer').remove();
  537.                 ++currentIndexColors;
  538.                 if (colors.hasOwnProperty(currentIndexColors))
  539.                     loadImages(colors[currentIndexColors]);
  540.             }
  541.         });
  542.     }
  543. }
  544.  
  545. function loadImagesBackground()
  546. {
  547.     for (var i in colors)
  548.         addLoader($('.group-color[data-color="' + colors[i] + '"]'));
  549.  
  550.     if (colors.hasOwnProperty(currentIndexColors))
  551.         loadImages(colors[currentIndexColors]);
  552. }
  553.  
  554. /**
  555.  * @param color
  556.  */
  557. function displayColorGroup(color)
  558. {
  559.     $('#square-color .square.square-color.border-select').removeClass('border-select');
  560.     $('.hide-off').removeClass('hide-off').addClass('hide-on');
  561.     $('#square-color .square.square-color[data-color="' + color + '"]').addClass('border-select');
  562.     var $groupColor = $('.group-color[data-color="' + color + '"]');
  563.     $groupColor.removeClass('hide-on').addClass('hide-off');
  564. }
  565.  
  566. /**
  567.  * @param $square
  568.  * @param color
  569.  */
  570. function applySquareColorProperties($square, color)
  571. {
  572.     $square
  573.         .attr('data-color', color)
  574.         .attr('data-tooltip', arrayColorName[color])
  575.         .attr('data-position', 'top center')
  576.         .css({'background-color' : arrayColor[color], 'cursor' : 'pointer'})
  577.     ;
  578. }
  579.  
  580. function initDisplayColors()
  581. {
  582.     var $squarePosition = $('<div class="square-position"></div>');
  583.     for (var value in arrayColor)
  584.     {
  585.         if (arrayColor.hasOwnProperty(value))
  586.         {
  587.             var $square = $('<div class="square square-color"></div>');
  588.             var $tooltipSquare = $('<div class="square square-color"></div>');
  589.             applySquareColorProperties($square, value);
  590.             applySquareColorProperties($tooltipSquare, value);
  591.             $squarePosition.append($square);
  592.             $gridItemPopupColorContainer.append($tooltipSquare);
  593.         }
  594.     }
  595.     $('#square-color').append($squarePosition);
  596.  
  597.     displayColorGroup('whitm');
  598.     checkDataLoad();
  599. }
  600.  
  601. /**
  602.  * @param $colorContainer
  603.  * @param item
  604.  * @param orientation
  605.  */
  606. function processItem($colorContainer, item, orientation)
  607. {
  608.     $colorContainer.prepend(newImage(item, orientation));
  609. }
  610.  
  611. function initDisplayModules()
  612. {
  613.     var $sizeContainer = $('#size-container');
  614.     for (var size in sortModulesBySize)
  615.     {
  616.         $sizeContainer.append('<a id="button-' + size + '" class="item" data-tab="' + size.substring(0, 2) + "x" + size.substring(0, 2) + '" style="left: 22.5%;">' + size.substring(0, 2) + "x" + size.substring(0, 2) + '</button>');
  617.         var $moduleContainer = $('<div id="modules-' + size + '" class="ui bottom attached tab segment objectDrag" data-tab="' + size + '" style="border-top: 0;border-bottom: 0;position: static;"></div>');
  618.         $('#contain-size-product').append($moduleContainer);
  619.  
  620.         for (var color in sortModulesBySize[size])
  621.         {
  622.             var $colorContainer = $('<div class="group-color hide-on" data-color="' + color + '" data-loaded="false"></div>');
  623.             $moduleContainer.append($colorContainer);
  624.             onLine = 0;
  625.             for (var type in sortModulesBySize[size][color])
  626.             {
  627.                 for (var ref in sortModulesBySize[size][color][type])
  628.                 {
  629.                     var item = sortModulesBySize[size][color][type][ref];
  630.                     loader_module[item.id] = true;
  631.                     if (item.hasOwnProperty('imageConfigurator'))
  632.                     {
  633.                         processItem($colorContainer, item, 0);
  634.                         if (item.canRotate != false)
  635.                         {
  636.                             for (var rotate = 90; rotate < 360; rotate += 90)
  637.                             {
  638.                                 processItem($colorContainer, item, rotate);
  639.                             }
  640.                         }
  641.                     }
  642.                 }
  643.             }
  644.         }
  645.     }
  646.  
  647.     $('#contain-size-product img.dragme').popup({
  648.         on: 'hover',
  649.         delay: {
  650.             show: 500,
  651.             hide: 0
  652.         }
  653.     });
  654.  
  655.     $('#button-1515').addClass('active');
  656.     $('#modules-1515').addClass('active');
  657.  
  658.     if (loadComposition()) {
  659.         Draw();
  660.         getCompositionPrice();
  661.         DisplayMenuAction();
  662.     }
  663.     else
  664.         DisableMenuAction();
  665.  
  666.     //if (!is_safari) {
  667.     loadImagesBackground();
  668.     //}
  669.  
  670.     hideLoaderGrid();
  671. }
  672.  
  673.  
  674. function Draw() {
  675.     for (var x in grid)
  676.     {
  677.         if (grid.hasOwnProperty(x))
  678.         {
  679.             for (var y in grid[x])
  680.             {
  681.                 if (grid[x].hasOwnProperty(y) && itemExistsInGrid(x, y))
  682.                 {
  683.                     if (!moduleIsPresent(x, y))
  684.                     {
  685.                         var item = grid[x][y];
  686.                         if (!item.isVirtual)
  687.                         {
  688.                             see_url_save_delete.hasObject = 1;
  689.                             addModule(item.code, x, y, item.orientation);
  690.                         }
  691.                     }
  692.                 }
  693.             }
  694.         }
  695.     }
  696. }
  697.  
  698. /**
  699.  * @param name_compo
  700.  * @param hasCaps
  701.  */
  702. function compositionToJson(name_compo, hasCaps)
  703. {
  704.  
  705.     var result = {
  706.         data : {},
  707.         hasCaps : hasCaps,
  708.         name : name_compo
  709.     };
  710.  
  711.     for (var x in grid) {
  712.         if (grid.hasOwnProperty(x)) {
  713.             for (var y in grid[x]) {
  714.                 if (grid[x].hasOwnProperty(y))
  715.                 {
  716.                     var key = x + ':' + y;
  717.                     var item = grid[x][y];
  718.                     if (itemExistsInGrid(x, y) && !item.isVirtual)
  719.                         result['data'][key] = item;
  720.                 }
  721.             }
  722.         }
  723.     }
  724.     return JSON.stringify(result);
  725. }
  726.  
  727. /**
  728.  * @param compositionName
  729.  * @param hasCaps
  730.  * @param isSave
  731.  * @param callback
  732.  */
  733. function saveGrid(compositionName, hasCaps, isSave, callback)
  734. {
  735.     var json = compositionToJson(compositionName, hasCaps);
  736.  
  737.     var endpoint = API_URL + '/compositions/save';
  738.     if (current_save.id != null && IS_EDIT)
  739.         endpoint = endpoint + '/' + current_save.id;
  740.  
  741.     $.post(
  742.         endpoint,
  743.         {
  744.             data: json,
  745.             isSave: isSave
  746.         },
  747.         null,
  748.         'json'
  749.     ).done(callback);
  750. }
  751.  
  752. /**
  753.  * @param price
  754.  * @param currencyCode
  755.  * @returns {string}
  756.  */
  757. function formatPrice(price, currencyCode)
  758. {
  759.     return parseFloat((Math.round(price) / 100)).toFixed(2) + ' ' + currencyCode;
  760. }
  761.  
  762. /**
  763.  * @param $list
  764.  * @param product
  765.  * @param quantity
  766.  * @param currencyCode
  767.  */
  768. function addProductInPriceList($list, product, quantity, currencyCode)
  769. {
  770.     var $line = $('<div class="module-line"></div>');
  771.  
  772.     var $name = $('<span class="left floated"><span class="square-color" style="background-color: ' + arrayColor[product.color] + ';"></span> ' + product.name + ' x' + quantity + ' </div>');
  773.     var $price = $('<span class="right floated">' + formatPrice((product.price * quantity), currencyCode) + '</div>');
  774.  
  775.     $line.append($name);
  776.     $line.append($price);
  777.     $list.append($line);
  778. }
  779.  
  780. function handleProducts($list, products, currencyCode)
  781. {
  782.     for (var key in products)
  783.     {
  784.         if (products.hasOwnProperty(key))
  785.         {
  786.             var productQuantity = products[key];
  787.             addProductInPriceList($list, productQuantity.product, productQuantity.quantity, currencyCode);
  788.         }
  789.     }
  790. }
  791.  
  792. function addTotalPrice($list, trans, formattedPrice)
  793. {
  794.     $list.append('<div class="total-line"><span class="left floated">' +  trans + '</span><span class="right floated">' + formattedPrice + '</span></div>');
  795.  
  796. }
  797.  
  798. function getCompositionPrice()
  799. {
  800.     var $loader = $('<div class="ui active inverted dimmer"><div class="ui mini loader"></div></div>');
  801.     $('#configurator-composition-menu').append($loader);
  802.     var json = compositionToJson();
  803.     $.post(API_URL + '/compositions/price', { data: json }, null, 'json')
  804.         .done(function(success) {
  805.             if (success.success)
  806.             {
  807.                 var $list = $('#configurator-composition-menu-list');
  808.                 var transPriceNoCaps = $list.data('trans-price-no-caps');
  809.                 var transPriceWithCaps = $list.data('trans-price-with-caps');
  810.                 var transOrder = $list.data('trans-order');
  811.  
  812.                 var data = success.data;
  813.                 var currencyCode = data.currencyCode;
  814.  
  815.                 $list.empty();
  816.  
  817.                 handleProducts($list, data.modules, currencyCode);
  818.                 if(data.priceNoCaps > 0)
  819.                     addTotalPrice($list, transPriceNoCaps, formatPrice(data.priceNoCaps, currencyCode));
  820.  
  821.                 $('#order-modal-no-caps-price').empty().append(formatPrice(data.priceNoCaps, currencyCode));
  822.  
  823.                 handleProducts($list, data.caps, currencyCode);
  824.                 if(data.priceWithCaps > 0)
  825.                     addTotalPrice($list, transPriceWithCaps, formatPrice(data.priceWithCaps, currencyCode));
  826.  
  827.                 $('#order-modal-with-caps-price').empty().append(formatPrice(data.priceWithCaps, currencyCode));
  828.  
  829.                 var $orderButton = $('<button class="small fluid ui red button" id="configurator-order-button">' + transOrder + '</button>');
  830.                 $list.prepend($orderButton);
  831.                 $orderButton.click(orderButtonClicked);
  832.  
  833.                 $('#configurator-composition-menu-price').empty().append(formatPrice(data.priceNoCaps, currencyCode));
  834.                 $loader.remove();
  835.             }
  836.         })
  837. }
  838.  
  839. /**
  840.  * @returns {boolean}
  841.  */
  842. function loadComposition()
  843. {
  844.     if (!IS_LOAD)
  845.         return false;
  846.  
  847.     if (IS_EDIT)
  848.     {
  849.         current_save.id = COMPOSITION_ID;
  850.         current_save.name = COMPOSITION_NAME;
  851.     }
  852.  
  853.     for (var posRaw in COMPOSITION_GRID)
  854.     {
  855.         if ( COMPOSITION_GRID.hasOwnProperty(posRaw)) {
  856.             var data =  COMPOSITION_GRID[posRaw];
  857.             var code = data.code;
  858.             if (product.hasOwnProperty(code) && data.isVirtual == false)
  859.             {
  860.                 var pos = posRaw.split(':');
  861.                 addItemToGrid(product[code], code , data.orientation, pos[0], pos[1]);
  862.             }
  863.         }
  864.     }
  865.     return true;
  866. }
  867.  
  868. /**
  869.  * @param target
  870.  * @returns {string}
  871.  */
  872. function addLoader(target)
  873. {
  874.     var $loader = $('<div class="ui active inverted dimmer"><div class="ui text loader">Loading</div></div>');
  875.     target.append($loader);
  876.     return $loader;
  877. }
  878.  
  879. /**
  880.  * @param loader
  881.  */
  882. function removeLoader(loader)
  883. {
  884.     loader.remove();
  885. }
  886.  
  887. /**
  888.  * @param id
  889.  * @param onApproveCallback
  890.  * @param onDenyCallback
  891.  * @returns {jQuery}
  892.  */
  893. function showModal(id, onApproveCallback, onDenyCallback)
  894. {
  895.     return $(id).modal({
  896.         blurring: true,
  897.         inverted: true,
  898.         selector    : {
  899.             close: '.close',
  900.             approve: '.actions .positive',
  901.             deny: '.actions .negative'
  902.         },
  903.         onDeny: onDenyCallback !== undefined ? onDenyCallback : function () {},
  904.         onApprove: onApproveCallback !== undefined ? onApproveCallback : function () {}
  905.     }).modal('setting', 'transition', 'vertical flip').modal('show');
  906. }
  907.  
  908. function hideModal(id)
  909. {
  910.     $(id).modal('setting', 'transition', 'vertical flip').modal('hide');
  911. }
  912.  
  913. /**
  914.  * @param data
  915.  */
  916. function loginModalHandleError(data)
  917. {
  918.     if (data.hasOwnProperty('responseJSON'))
  919.     {
  920.         var error = data.responseJSON.error;
  921.         $('#login-modal-content').prepend('<div class="ui negative message" id="login-modal-error-message"><div class="header">' + error + '</div></div>');
  922.     }
  923. }
  924.  
  925.  
  926. function loginModalHandleSuccess()
  927. {
  928.     hideModal('#login-modal');
  929.     showModal('#save-modal');
  930. }
  931.  
  932. /**
  933.  * @param e
  934.  * @returns {string}
  935.  */
  936. function loginModalButtonClicked(e)
  937. {
  938.     e.preventDefault();
  939.     $('#login-modal-error-message').remove();
  940.     return addLoader($('#login-modal-content'));
  941. }
  942.  
  943. /**
  944.  * @param $target
  945.  * @param x
  946.  * @param y
  947.  * @param ref
  948.  * @param callback
  949.  */
  950. function handleInPopUpClick($target, x, y, ref, callback)
  951. {
  952.     $target.data('x', x);
  953.     $target.data('y', y);
  954.     $target.data('code', ref);
  955.     $target.click(callback);
  956. }
  957.  
  958. $(function () {
  959.  
  960.     $('#composition-name-input').val(COMPOSITION_NAME);
  961.  
  962.     // -----------------------------------------------------------------------
  963.     // Events
  964.     // -----------------------------------------------------------------------
  965.  
  966.     $.getJSON(API_URL + '/products', function(json)
  967.     {
  968.  
  969.         $.each(json, function (i, item) {
  970.             if (item.hasOwnProperty('imageConfigurator') && item.hasOwnProperty('code') && item.hasOwnProperty('size') && item.imageConfigurator != null) {
  971.                 if (!(sortModulesBySize.hasOwnProperty(item.size)))
  972.                     sortModulesBySize[item.size] = {};
  973.                 if (!((sortModulesBySize[item.size]).hasOwnProperty(item.color)))
  974.                     sortModulesBySize[item.size][item.color] = {};
  975.                 if (!((sortModulesBySize[item.size][item.color]).hasOwnProperty(item.type)))
  976.                     sortModulesBySize[item.size][item.color][item.type] = {};
  977.                 sortModulesBySize[item.size][item.color][item.type][item.code] = item;
  978.  
  979.                 if (equivalences.hasOwnProperty(item.size))
  980.                     item['base'] = equivalences[item.size];
  981.                 else
  982.                     item['base'] = 1;
  983.  
  984.                 product[item.code] = item;
  985.             }
  986.         });
  987.  
  988.         initDisplayModules();
  989.         initDisplayColors();
  990.  
  991.         $('.square-color').click(function() {
  992.             displayColorGroup($(this).data('color'));
  993.         });
  994.  
  995.         $('#button-1515').click(function(){
  996.             $('#modules-1515').addClass('active');
  997.             $('#button-1515').addClass('active');
  998.             $('.product-configurator').addClass('hide-on');
  999.             $('#modules-3030').removeClass('active');
  1000.             $('#button-3030').removeClass('active');
  1001.         });
  1002.  
  1003.         $('#button-3030').click(function(){
  1004.             $('#button-1515').removeClass('active');
  1005.             $('#modules-1515').removeClass('active');
  1006.             $('.product-configurator').addClass('hide-on');
  1007.             $('#modules-3030').addClass('active');
  1008.             $('#button-3030').addClass('active');
  1009.         });
  1010.  
  1011.         var $dragImg = $('.objectDrag img');
  1012.  
  1013.         $dragImg.draggable({
  1014.             helper: 'clone',
  1015.             cursorAt: {top:  SQUARE_SIZE / 2, left: SQUARE_SIZE / 2},
  1016.             start: function (event, ui) {
  1017.                 var code = $(this).data('code');
  1018.                 if (product.hasOwnProperty(code)) {
  1019.                     var item = product[code];
  1020.                     ghost.item = item;
  1021.                     ui.helper.css({
  1022.                         'width': SQUARE_SIZE * item.base,
  1023.                         'height': SQUARE_SIZE * item.base,
  1024.                         'opacity' : .5,
  1025.                         'z-index' : 115
  1026.                     });
  1027.                 }
  1028.             },
  1029.  
  1030.             drag: function(ev)
  1031.             {
  1032.                 hoverTrash();
  1033.                 handleMouseClick(ev, function(x, y)
  1034.                 {
  1035.                     ghost.x = x;
  1036.                     ghost.y = y;
  1037.                     $('#ghost').remove();
  1038.                     if (canDropModule(ghost.item, x, y))
  1039.                         displayGhost();
  1040.                 });
  1041.             },
  1042.  
  1043.             stop: function (ev) {
  1044.                 $('#ghost').remove();
  1045.                 var $this = $(this);
  1046.                 if (!isHoverBin)
  1047.                     handleMouseClick(ev, function(x, y, mouseX, mouseY)
  1048.                     {
  1049.                         var code = $this.data('code');
  1050.                         if (product.hasOwnProperty(code))
  1051.                         {
  1052.                             var item = product[code];
  1053.                             var rotate = $this.data('rotate');
  1054.                             if (mouseX > 0 && mouseX < GRID_SIZE && mouseY > 0 && mouseY < GRID_SIZE)
  1055.                             {
  1056.                                 if (canDropModule(item, x, y))
  1057.                                     addItemToGrid(item, code, rotate, x, y);
  1058.                             }
  1059.                         }
  1060.                     });
  1061.                 getCompositionPrice();
  1062.             }
  1063.         });
  1064.         createGrid(GRID_SIZE,VIEW_WIDTH, VIEW_HEIGHT, MOVE_WIDTH, MOVE_HEIGHT);
  1065.         checkDataLoad();
  1066.     });
  1067.  
  1068.     $('.trash').hover(
  1069.         function() { isHoverBin = true },
  1070.         function () { isHoverBin = false }
  1071.     );
  1072.  
  1073.  
  1074.     $noCapsOrderButton.click(function () {
  1075.         orderComposition(false);
  1076.     });
  1077.     $withCapsOrderButton.click(function () {
  1078.         orderComposition(true);
  1079.     });
  1080.  
  1081.  
  1082.  
  1083.     $loginModalButton.click(function(e) {
  1084.         var $loader = loginModalButtonClicked(e);
  1085.         $.post(API_URL + '/users/login', {
  1086.             email: $('#email-login-input').val(),
  1087.             password: $('#password-login-input').val()
  1088.         }, function () { loginModalHandleSuccess() ; }, 'json')
  1089.             .fail(function (data) {
  1090.                 loginModalHandleError(data)
  1091.             })
  1092.             .always(function() {
  1093.                 removeLoader($loader);
  1094.             })
  1095.     });
  1096.  
  1097.  
  1098.     $registerModalButton.click(function (e) {
  1099.         var $loader = loginModalButtonClicked(e);
  1100.         $.post(API_URL + '/users/register', {
  1101.             email: $('#email-register-input').val(),
  1102.             password: $('#password-register-input').val(),
  1103.             passwordConfirmation : $('#password-confirmation-register-input').val()
  1104.         }, function () { loginModalHandleSuccess() ; }, 'json')
  1105.             .fail(function (data) {
  1106.                 loginModalHandleError(data)
  1107.             })
  1108.             .always(function() {
  1109.                 removeLoader($loader);
  1110.             })
  1111.     });
  1112.  
  1113.     $downloadLink.click(function(){
  1114.         var pdfLink = $('#download-pdf-link');
  1115.         pdfLink.addClass('loading');
  1116.         showModal('#download-modal', null, null);
  1117.         saveGrid(null, false, false, function(data) {
  1118.             pdfLink
  1119.                 .attr('href', API_URL + '/compositions/download/pdf/composition_' + data.publicId + '.pdf')
  1120.                 .removeClass('loading')
  1121.             ;
  1122.         });
  1123.  
  1124.     });
  1125.  
  1126.     $saveGridButton.click(function (e) {
  1127.         e.preventDefault();
  1128.         $saveGridButton.addClass('loading');
  1129.         saveGrid($('#composition-name-input').val(), false, true, function(data) {
  1130.             current_save.id = data.id;
  1131.             current_save.name = data.name;
  1132.             IS_EDIT = true;
  1133.             $saveGridButton.removeClass('loading');
  1134.             hideModal('#save-modal');
  1135.         });
  1136.     });
  1137.  
  1138.     $shareGrid.click(function () {
  1139.         showModal('#share-modal');
  1140.     });
  1141.  
  1142.     $shareGridButton.click(function(e) {
  1143.         e.preventDefault();
  1144.  
  1145.         $('#share-modal-error-message').remove();
  1146.         $shareGridButton.addClass('loading');
  1147.  
  1148.         saveGrid(current_save.name, false, false, function(data) {
  1149.             $.post(API_URL + '/compositions/share/' + data.id, {
  1150.                 email: $('#share-email-input').val(),
  1151.                 message: $('#share-message-textarea').val()
  1152.             }, function() {
  1153.                 hideModal('#share-modal');
  1154.             }, 'json')
  1155.                 .fail(function (data) {
  1156.                     if (data.hasOwnProperty('responseJSON'))
  1157.                     {
  1158.                         var error = data.responseJSON.error;
  1159.                         $('#share-modal-content').prepend('<div class="ui negative message" id="share-modal-error-message"><div class="header">' + error + '</div></div>');
  1160.                     }
  1161.                 })
  1162.                 .always(function () {
  1163.                     $shareGridButton.removeClass('loading');
  1164.                 })
  1165.             ;
  1166.         });
  1167.     });
  1168.  
  1169.     $saveGrid.click(function(e){
  1170.         if (IS_LOGGED)
  1171.         {
  1172.             $('#composition-name-input').val(current_save.name);
  1173.             showModal('#save-modal');
  1174.         }
  1175.         else
  1176.             showModal('#login-modal');
  1177.         return e.preventDefault();
  1178.     });
  1179.  
  1180.     $remove_all.click(function(){
  1181.         showModal('#delete-modal', function() {
  1182.             removeModule_all();
  1183.         });
  1184.     });
  1185.  
  1186.     $grid.draggable({
  1187.         containment: '.move_grid'
  1188.     });
  1189.  
  1190.     $(document).on('click', '.grid-item', function(ev) {
  1191.  
  1192.         var $popUp = $('#grid-item-popup-container').clone();
  1193.         $popUp.addClass('active');
  1194.         var $target = $(this);
  1195.         var $gridItemPopupColorContainer = $popUp.find('#grid-item-popup-color-container');
  1196.  
  1197.         var x = $target.data('x');
  1198.         var y = $target.data('y');
  1199.  
  1200.         if (itemExistsInGrid(x, y))
  1201.         {
  1202.             var item = grid[x][y];
  1203.             var p = product[item.code];
  1204.             $popUp.data('code', item.code);
  1205.  
  1206.             // Change color
  1207.             $gridItemPopupColorContainer.find('.square-color[data-color="' + p.color + '"]').addClass('border-select');
  1208.  
  1209.             // Hide rotate icons
  1210.             if (!p.canRotate)
  1211.             {
  1212.                 $popUp.find('.rotate').remove();
  1213.                 $popUp.find('.rotate-inverse').remove();
  1214.             }
  1215.  
  1216.             $('.grid-item-popup-container.active').remove();
  1217.             $grid.prepend($popUp);
  1218.  
  1219.             var popup = $target.popup({
  1220.                 popup: $popUp,
  1221.                 exclusive: true,
  1222.                 hoverable: true,
  1223.                 on: 'manual',
  1224.                 inline: true,
  1225.                 variation: 'wide',
  1226.                 position: 'top center'
  1227.             }).popup('show');
  1228.  
  1229.             handleInPopUpClick($('.grid-item-popup-container.active button.rotate'), x, y, item.code, function () {
  1230.                 var $this = $(this);
  1231.                 rotateModuleInGrid($this.data('x'), $this.data('y'), false);
  1232.             });
  1233.  
  1234.             handleInPopUpClick($('.grid-item-popup-container.active button.rotate-inverse'), x, y, item.code, function () {
  1235.                 var $this = $(this);
  1236.                 rotateModuleInGrid($this.data('x'), $this.data('y'), true);
  1237.             });
  1238.  
  1239.             handleInPopUpClick($('.grid-item-popup-container.active button.delete'), x, y, item.code, function () {
  1240.                 var $this = $(this);
  1241.                 var x = $this.data('x');
  1242.                 var y = $this.data('y');
  1243.                 popup.popup('hide');
  1244.                 deleteModule(x, y);
  1245.                 removeModuleInGrid(x ,y);
  1246.                 Draw();
  1247.                 getCompositionPrice();
  1248.             });
  1249.  
  1250.             handleInPopUpClick($('.grid-item-popup-container.active .square.square-color'), x, y, item.code, function() {
  1251.                 var $this = $(this);
  1252.                 var code = $this.data('code');
  1253.                 var color = $this.data('color');
  1254.                 var rotate = (getModuleInGrid(x ,y)).data('rotate');
  1255.                 var newRef = (p.size + '-' + p.type + '-' + color).toUpperCase();
  1256.                 $gridItemPopupColorContainer.find('.square-color').removeClass('border-select');
  1257.                 $gridItemPopupColorContainer.find('.square-color[data-color="' + color + '"]').addClass('border-select');
  1258.                 deleteModule(x, y);
  1259.                 removeModuleInGrid(x, y);
  1260.                 addItemToGrid(p, newRef, rotate, x, y);
  1261.                 Draw();
  1262.                 getCompositionPrice();
  1263.             });
  1264.         }
  1265.     });
  1266.  
  1267. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement