Advertisement
Guest User

Untitled

a guest
Oct 31st, 2014
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.14 KB | None | 0 0
  1. var itemsList = {},
  2. clientsList = {},
  3. store = {},
  4. prevRow,
  5. prevCol = 0,
  6. showReference = document.getElementById('show-reference'),
  7. tableHeader = document.getElementById('table-header'),
  8. docsWrapper = document.getElementById('docsWrapper'),
  9. firstDateInput = document.getElementById('firstDate'),
  10. secDateInput = document.getElementById('secDate'),
  11. checkBox = document.getElementById('checkBox'),
  12. clientsWithDocsBtn = document.getElementById('all-clients-with-docs'),
  13. table = document.getElementById('table');
  14.  
  15. sendRequestToServer(['objects', 'ЛЕЙДИ СОФИЯ АД'], 'storesList');
  16.  
  17. function sendRequestToServer(arr, wanted) {
  18. var request = new XMLHttpRequest();
  19. request.onreadystatechange = function () {
  20. if (request.readyState == 4 && request.status == 200) {
  21. if (wanted == 'storesList') {
  22. wanted = request.responseText;
  23. wanted = JSON.parse(wanted);
  24. fillStoresSelect(wanted);
  25. }
  26. if (wanted == 'store') {
  27. wanted = request.responseText;
  28. wanted = wanted.replace(/""/g, '"');
  29. wanted = JSON.parse(wanted);
  30.  
  31. showReference.disabled = false;
  32. }
  33. if (wanted == 'documents') {
  34. wanted = JSON.parse(request.responseText);
  35. changeStore(wanted);
  36. generateRef(wanted);
  37. buildTable();
  38. fillSelectWithClients();
  39. }
  40. }
  41. }
  42. request.open("POST", "http://192.168.1.184:8000/pm", true);
  43. request.send(JSON.stringify(arr));
  44. }
  45.  
  46. function fillStoresSelect(arr) {
  47. var option = document.createElement('option');
  48. for (var i = 0; i < arr.length; i++) {
  49. var optionClone = option.cloneNode(true);
  50. optionClone.innerText = arr[i].slice(arr[i].lastIndexOf(':') + 1);
  51. optionClone.value = '{"warehouse":' + '"' + arr[i] + '"}';
  52. document.getElementById('storesSelect').appendChild(optionClone);
  53. }
  54. }
  55.  
  56. document.getElementById('storesSelect').onchange = function () {
  57. var selected = this.value;
  58. if (selected == 'Всички') {
  59. showReference.disabled = true;
  60. sendRequestToServer(['items', '{}'], 'store');
  61. } else {
  62. sendRequestToServer(['items', selected], 'store');
  63. }
  64. }
  65. var testArr = [];
  66. //Extract all items and clients from the main JSON and put them into two associative arrays
  67. function generateRef(obj) {
  68. for (var a = 0; a < obj.length; a++) {
  69. fillclientsList(obj[a].partner, obj[a]);
  70. for (var b = 0; b < obj[a].Lines.length; b++) {
  71. checkItems(obj[a].partner, obj[a].Lines[b]);
  72. }
  73. }
  74. }
  75.  
  76. //Convert store JSON into an object
  77. function changeStore(currentStore) {
  78. store = {};
  79. for (var i = 0; i < currentStore.length; i++) {
  80. store[currentStore[i].name] = currentStore[i];
  81. }
  82. }
  83.  
  84. //on every merchandise if array fill clients that have it with whole quantity
  85. function checkItems(initialClient, march) {
  86. var client = (initialClient) ? initialClient.slice(initialClient.lastIndexOf(':') + 1) : 'No Name';
  87. var itemName = march.item.slice(march.item.lastIndexOf(':') + 1);
  88. if (itemsList[itemName]) {
  89.  
  90. if (itemsList[itemName][client]) {
  91. (march.quantity) ? itemsList[itemName][client] = Number(itemsList[itemName][client]) + Number(march.quantity) : itemsList[itemName][client];
  92. } else {
  93. (march.quantity) ? itemsList[itemName][client] = Number(march.quantity) : 0;
  94. }
  95. } else {
  96. itemsList[itemName] = {};
  97. (march.quantity) ? itemsList[itemName][client] = Number(march.quantity) : 0;
  98. }
  99. }
  100.  
  101. //all clients with theys documents and full info on document
  102. function fillclientsList(initalName, obj) {
  103. var name = (initalName) ? initalName.slice(initalName.lastIndexOf(':') + 1) : 'No Name';
  104.  
  105. if (clientsList[name]) {
  106. if (clientsList[name][obj.num]) {
  107. var newDocNumber = obj.num + '(new(' + (Math.floor(Math.random() * 10000) + 1) + '))';
  108. clientsList[name][newDocNumber] = {
  109. date: obj.date
  110. }
  111. fillClientDocumentWithItems(newDocNumber);
  112. return;
  113. } else {
  114. clientsList[name][obj.num] = {
  115. date: obj.date,
  116. };
  117. }
  118. } else {
  119. clientsList[name] = {};
  120. clientsList[name][obj.num] = {
  121. date: obj.date
  122. };
  123. }
  124.  
  125. fillClientDocumentWithItems(obj.num);
  126.  
  127. function fillClientDocumentWithItems(number) {
  128. var Items = {};
  129. for (var i = 0; i < obj.Lines.length; i++) {
  130. if (Items[obj.Lines[i].item]) {
  131. Items[obj.Lines[i].item].quantity += (obj.Lines[i].quantity) ? Number(obj.Lines[i].quantity) : 0;
  132. } else {
  133. Items[obj.Lines[i].item] = {};
  134. Items[obj.Lines[i].item].quantity = (obj.Lines[i].quantity) ? Number(obj.Lines[i].quantity) : 0;
  135. }
  136. }
  137. clientsList[name][number]['Items'] = Items;
  138. }
  139. }
  140.  
  141. function buildTable(reUse) {
  142. (function fillHeader() {
  143. var strArray = ['<div class="table-row"><div class="plain-cell">&nbsp;</div><div class="plain-cell">No</div>'],
  144. docArr = ['<div class="table-row"><div class="plain-cell">Док. номер</div><div class="plain-cell">&nbsp;</div>'],
  145. docDate = ['<div class="table-row"><div class="plain-cell">Док. дата</div><div class="plain-cell">&nbsp;</div>'];
  146. for (var key in clientsList) {
  147. if (reUse) {
  148. for (var prop in clientsList[key]) {
  149. var date = clientsList[key][prop].date;
  150. strArray.push('<div class="plain-cell no-print">' + key + '</div>')
  151. docArr.push('<div class="plain-cell">' + prop + '</div>');
  152. docDate.push('<div class="plain-cell">' + date.substr(6, 2) + '.' + date.substr(4, 2) + '.' + date.substr(0, 4) + '</div>');
  153. }
  154. }
  155. else {
  156. strArray.push('<div class="plain-cell no-print">' + key + '</div>');
  157. }
  158. }
  159. docArr.push('<div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div></div></div>')
  160. docDate.push('<div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div></div></div>')
  161. strArray.push('<div class="plain-cell">Общо планирани</div><div class="plain-cell">Количество от склад</div><div class="plain-cell">Блокирани</div><div class="plain-cell">Разлика</div></div>');
  162. if (reUse) {
  163. docsWrapper.innerHTML = docArr.join('') + docDate.join('');
  164. }
  165.  
  166. tableHeader.innerHTML = strArray.join('');
  167. resizeConteiners(tableHeader.children[0].children.length * 100 + 300);
  168. }());
  169.  
  170. (function fillRows() {
  171. var strArray = [],
  172. counter = 1,
  173. totalRowItems = 0;
  174.  
  175. for (var key in itemsList) {
  176. strArray.push('<div class="table-row"><div class="plain-cell">' + key + '</div><div class="plain-cell">' + counter + '</div>')
  177. for (var name in clientsList) {
  178. if (reUse) {
  179. var result = expandedRows(clientsList[name], key);
  180. strArray.push(result.html);
  181. totalRowItems += result.quantity;
  182. continue;
  183. }
  184. if (itemsList[key][name]) {
  185. strArray.push('<div class="plain-cell no-print">' + itemsList[key][name] + '</div>')
  186. totalRowItems += Number(itemsList[key][name]);
  187. } else {
  188. strArray.push('<div class="plain-cell no-print">&nbsp;</div>')
  189. }
  190. }
  191. var storeQuantity = 0,
  192. storeBlocked = 0;
  193. if (typeof (store[key]) != 'undefined') {
  194. storeQuantity = (typeof (store[key].quantity) == 'undefined') ? 0 : store[key].quantity;
  195. storeBlocked = (typeof (store[key].blocked) != 'undefined') ? store[key].blocked : 0;
  196. }
  197.  
  198. quantitydifference = Number(storeQuantity) - storeBlocked - totalRowItems;
  199. strArray.push('<div class="plain-cell">' + totalRowItems + '</div><div class="plain-cell">' + storeQuantity + '</div>' +
  200. '<div class="plain-cell">' + storeBlocked + '</div>' +
  201. '<div class="plain-cell">' + quantitydifference + '</div></div>');
  202. counter++;
  203. totalRowItems = 0;
  204. }
  205.  
  206. if (reUse) {
  207. table.innerHTML = setSerialNumberRow(clientsList, true);
  208. }
  209. else {
  210. table.innerHTML = setSerialNumberRow(clientsList, false);
  211. }
  212. table.innerHTML += strArray.join('');
  213. printTotalQuantity();
  214. }());
  215. }
  216.  
  217. //Build row with serial number for each client or document
  218. function setSerialNumberRow(obj, isExpanded) {
  219. var strArr = [],
  220. prevProp,
  221. counter = 1;
  222.  
  223. strArr.push('<div class="table-row no-print"><div class="plain-cell">&nbsp;</div><div class="plain-cell">No</div>');
  224. for (var prop in obj) {
  225. strArr.push('<div class="plain-cell">' + counter + '</div>');
  226. counter++;
  227. if (isExpanded) {
  228. var countKeys = 0;
  229. for (var key in obj[prop]) {
  230. countKeys++;
  231. }
  232. for (var i = 0; i < countKeys - 1; i++) {
  233. strArr.push('<div class="plain-cell">&nbsp;</div>');
  234. }
  235. }
  236. prevProp = prop;
  237. }
  238. strArr.push('<div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div></div>');
  239. return strArr.join('');
  240. }
  241.  
  242. //expands basic table after click on chechbox
  243. function expandedRows(obj, itemName) {
  244. var strArray = [];
  245. totalRowItems = 0;
  246. for (var key in obj) {
  247. if (obj[key].Items[itemName]) {
  248. strArray.push('<div class="plain-cell no-print">' + obj[key].Items[itemName].quantity + '</div>');
  249. totalRowItems += Number(obj[key].Items[itemName].quantity);
  250. } else {
  251. strArray.push('<div class="plain-cell no-print">&nbsp;</div>');
  252. }
  253. }
  254. return {
  255. html: strArray.join(''),
  256. quantity: totalRowItems
  257. }
  258. }
  259.  
  260. //Visualize all documents from client chosen by click on the header
  261. tableHeader.onclick = function (e) {
  262.  
  263. var target = (typeof (event) != 'undefined') ? event.srcElement.outerText : e.target.innerHTML,
  264. checkBiggerWidth = 0;
  265.  
  266. if (target == 'No' || target == 'Общо планирани' || target == 'Количество от склад' ||
  267. target == 'Блокирани' || target == 'Разлика' || target == '' || target.length == 1) {
  268. return;
  269. }
  270.  
  271. if (target == 'Всички') {
  272. clientsWithDocsBtn.disabled = false;
  273. clientsWithDocsBtn.checked = false;
  274. if (!checkBox.checked) {
  275. checkBox.click();
  276. }
  277. docsWrapper.style.display = 'none';
  278. buildTable();
  279. return;
  280. }
  281. docsWrapper.style.display = '';
  282. changeHeaderAfterClick(target);
  283. clientsWithDocsBtn.disabled = true;
  284. resizeConteiners(docsWrapper.childNodes[0].children.length * 100 + 300)
  285. };
  286.  
  287. //after click on some cell change color of a cell row and col
  288. table.onclick = function (ev) {
  289. var target = (typeof (event) != 'undefined') ? event.srcElement : ev.target;
  290. if (target.className == 'plain-cell no-print') {
  291. var rows = document.querySelectorAll('#table .table-row');
  292.  
  293. if (prevCol <= rows[0].children.length) {
  294. for (var z = 0; z < rows.length; z++) {
  295. rows[z].children[prevCol].style.backgroundColor = '';
  296. }
  297. }
  298. if (prevCol == checkForPrevCol(target.parentNode, target) && prevRow == target.parentNode) {
  299. prevRow.style.backgroundColor = '';
  300. prevCol = 0;
  301. return;
  302. }
  303. prevCol = checkForPrevCol(target.parentNode, target);
  304. for (var z = 0; z < rows.length; z++) {
  305. rows[z].children[prevCol].style.backgroundColor = 'lightBlue';
  306. }
  307.  
  308. if (prevRow) {
  309. prevRow.style.backgroundColor = '';
  310. }
  311. prevRow = target.parentNode;
  312. prevRow.style.backgroundColor = 'lightblue';
  313. target.style.backgroundColor = '#bde0eb';
  314. }
  315. };
  316.  
  317. function checkForPrevCol(parentEl, targetCell) {
  318. for (var i = 0; i < parentEl.children.length; i++) {
  319. if (parentEl.children[i] == targetCell) {
  320. return i;
  321. }
  322. }
  323. return -1;
  324. }
  325.  
  326. //fill table with data for clicked client
  327. function fillTableAfterClick(targetName) {
  328. var strArray = [],
  329. invoiceNumber = [],
  330. invoiceDate = [],
  331. rowCounter = 1,
  332. iterationCounter = 0,
  333. countRowItems = 0;
  334.  
  335. invoiceNumber.push('<div class="table-row no-print"><div class="plain-cell">Док.ном</div><div class="plain-cell">&nbsp;</div>')
  336. invoiceDate.push('<div class="table-row no-print"><div class="plain-cell">Дата</div><div class="plain-cell">&nbsp;</div>')
  337.  
  338. var itemsArr = extractItemsFromClient(clientsList[targetName]);
  339. for (var name in itemsArr) {
  340. strArray.push('<div class="table-row"><div class="plain-cell">' + name + '</div><div class="plain-cell">' + rowCounter + '</div>');
  341. var clientKeys = 0;
  342. for (var keys in clientsList[targetName]) {
  343. clientKeys++;
  344. }
  345. for (var key in clientsList[targetName]) {
  346. if (iterationCounter < clientKeys) {
  347. var currentDate = clientsList[targetName][key].date;
  348. invoiceNumber.push('<div class="plain-cell">' + key + '</div>')
  349. invoiceDate.push('<div class="plain-cell">' + currentDate.slice(6, currentDate.length) + '.' + currentDate.slice(4, 6) + '.' + currentDate.slice(0, 4) + '</div>')
  350. }
  351. if (clientsList[targetName][key].Items[name]) {
  352. strArray.push('<div class="plain-cell no-print">' + clientsList[targetName][key].Items[name].quantity + '</div>');
  353. countRowItems += Number(clientsList[targetName][key].Items[name].quantity);
  354. } else {
  355. strArray.push('<div class="plain-cell no-print">&nbsp;</div>');
  356. }
  357. iterationCounter++;
  358. }
  359. var storeQuantity = 0,
  360. storeBlocked = 0;
  361. if (typeof (store[key]) != 'undefined') {
  362. storeQuantity = (typeof (store[key].quantity) == 'undefined') ? 0 : store[key].quantity;
  363. storeBlocked = (typeof (store[key].blocked) != 'undefined') ? store[key].blocked : 0;
  364. }
  365. strArray.push('<div class="plain-cell">' + countRowItems + '</div><div class="plain-cell">' + storeQuantity + '</div>' +
  366. '<div class="plain-cell">' + storeBlocked + '</div><div class="plain-cell">' + quantitydifference + '</div>');
  367. strArray.push('</div>');
  368. countRowItems = 0;
  369. rowCounter++;
  370. }
  371. invoiceNumber.push('<div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div></div>')
  372. invoiceDate.push('<div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div><div class="plain-cell">&nbsp;</div></div>')
  373. docsWrapper.innerHTML = invoiceNumber.join('') + invoiceDate.join('');
  374. table.innerHTML = setSerialNumberRow(clientsList[targetName], false) + strArray.join('');
  375. printTotalQuantity();
  376. }
  377.  
  378. //fill footer with calculated data from colums
  379. function printTotalQuantity() {
  380. var strArray = ['<div class="table-row"><div class="plain-cell">Общо</div><div class="plain-cell">&nbsp;</div>'],
  381. sum = 0;
  382. for (var i = 2; i < table.children[0].children.length; i++) {
  383. for (var z = 1; z < table.children.length; z++) {
  384. sum += Number(table.children[z].children[i].innerHTML == '&nbsp;' ? '' : table.children[z].children[i].innerHTML);
  385. }
  386. if (i < table.children[0].children.length - 4) {
  387. strArray.push('<div class="plain-cell no-print">' + sum + '</div>')
  388. }
  389. else {
  390. strArray.push('<div class="plain-cell">' + sum + '</div>')
  391. }
  392. sum = 0;
  393. }
  394. strArray.push('</div>');
  395. table.innerHTML += strArray.join('');
  396. }
  397.  
  398. //extract only items that are in all clients
  399. function extractItemsFromClient(client) {
  400. var result = {};
  401. for (var doc in client) {
  402. for (var item in client[doc].Items) {
  403. if (!result[item]) result[item] = {};
  404. }
  405. }
  406. return result;
  407. }
  408.  
  409. showReference.onclick = checkIfDatesInputAreActive;
  410.  
  411. function fillSelectWithClients() {
  412. var strArray = [];
  413. if (firstDateInput.value && secDateInput.value) {
  414. strArray.push('<option>Всички</option>');
  415. for (var name in clientsList) {
  416. strArray.push('<option>' + name + '</option>');
  417. }
  418. }
  419. document.getElementById('clientSelect').innerHTML = strArray.join('');
  420. }
  421.  
  422. //change header with only clicked client name and empty cells; call fillTableAfterClick with client name
  423. function changeHeaderAfterClick(name) {
  424. tableHeader.innerHTML = '<div class="table-row"><div class="plain-cell">&nbsp;</div><div class="plain-cell">No</div><div class="plain-cell no-print">' + name + '</div><div class="plain-cell no-print" id="empty-cell"></div><div class="plain-cell">Общо планирани</div>' +
  425. '<div class="plain-cell">Количество от склад</div><div class="plain-cell">Блокирани</div><div class="plain-cell">Разлика</div></div>';
  426. fillTableAfterClick(name);
  427. clientsWithDocsBtn.checked = true;
  428. clientsWithDocsBtn.disabled = true;
  429. tableHeader.childNodes[0].firstChild.innerHTML = 'Всички';
  430. }
  431.  
  432. function checkIfDatesInputAreActive() {
  433. var clientSelectValue = document.getElementById('clientSelect').options[document.getElementById('clientSelect').selectedIndex].innerText,
  434. firstDateArr = (firstDateInput.value).split('-'),
  435. secDateArr = (secDateInput.value).split('-');
  436. if (firstDateInput.value && secDateInput.value) {
  437. checkBox.disabled = false;
  438.  
  439. if (clientSelectValue != 'Всички') {
  440. docsWrapper.style.display = '';
  441. changeHeaderAfterClick(clientSelectValue);
  442. if (!checkBox.checked) {
  443. checkBox.click();
  444. }
  445. resizeConteiners(docsWrapper.children[0].children.length * 100 + 300)
  446. return;
  447. }
  448.  
  449. clientsList = {};
  450. itemsList = {};
  451. //sending request for documents at given
  452. sendRequestToServer(['documents', 'ЛЕЙДИ СОФИЯ АД', firstDateArr.reverse().join(''), secDateArr.reverse().join(''), '', 'forward', '{}', 'false'], 'documents');
  453.  
  454. if (!checkBox.checked) {
  455. checkBox.click();
  456. }
  457. if (clientsWithDocsBtn.disabled) {
  458. clientsWithDocsBtn.disabled = false;
  459. }
  460. if (clientsWithDocsBtn.checked) {
  461. clientsWithDocsBtn.checked = false;
  462. }
  463. docsWrapper.style.display = 'none';
  464. }
  465. }
  466.  
  467. checkBox.onclick = function () {
  468. if (!this.checked) {
  469. document.head.innerHTML += '<style>.no-print{display:none}</style>';
  470. resizeConteiners(table.offsetWidth);
  471. docsWrapper.style.display = 'none';
  472. }
  473. else {
  474. document.head.removeChild(document.querySelectorAll('style')[0]);
  475. resizeConteiners(table.children[0].children.length * 100 + 300);
  476. if (clientsWithDocsBtn.checked) {
  477. docsWrapper.style.display = '';
  478. } else {
  479. docsWrapper.style.display = 'none';
  480. }
  481. }
  482. if (prevRow) {
  483. prevRow.style.backgroundColor = '';
  484. }
  485. };
  486.  
  487. clientsWithDocsBtn.onclick = function () {
  488. if (this.checked) {
  489. buildTable(true)
  490. docsWrapper.style.display = '';
  491. if (!checkBox.checked) checkBox.click();
  492. }
  493. else {
  494. buildTable();
  495. resizeConteiners(table.offsetWidth);
  496. docsWrapper.style.display = 'none';
  497. }
  498. };
  499.  
  500. function resizeConteiners(size) {
  501. docsWrapper.style.width = size + 'px';
  502. document.getElementById('main-wrapper').style.width = size + 2 + 'px';
  503. tableHeader.childNodes[0].style.width = size + 'px';
  504.  
  505. if (docsWrapper.children.length == 0) {
  506. return;
  507. }
  508. if (!document.getElementById('empty-cell')) {
  509. return;
  510. }
  511. if (docsWrapper.offsetWidth - 1000 < 0) {
  512. return;
  513. }
  514. document.getElementById('empty-cell').style.width = (docsWrapper.offsetWidth - 1000) + 'px';
  515. if (docsWrapper.children[0].children.length <= 7) {
  516. document.getElementById('empty-cell').style.display = 'none'
  517. }
  518. }
  519.  
  520. var datePickerBtns = document.querySelectorAll('.open-date-picker');
  521. for (var i = 0; i < datePickerBtns.length; i++) {
  522. datePickerBtns[i].onclick = generateDateForm;
  523. }
  524.  
  525. function generateDateForm(ev) {
  526. var datePicker = document.getElementById('date-picker');
  527.  
  528. //Set the main structure of the date-picker element;
  529. datePicker.innerHTML = '<div><button>&#9668;</button><span></span><button>&#9658;</button></div><span class="hor-line"></span><div id="date-picker-week"><span>Sun</span>' +
  530. '<span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span></div><span class="hor-line"></span><div id="date-picker-days"></div>';
  531.  
  532. var monthNames = ["January", "February", "March", "April", "May", "June",
  533. "July", "August", "September", "October", "November", "December"],
  534. month = datePicker.querySelectorAll('span')[0],
  535. startOrEndDate = this.previousSibling,
  536. currentMonth = Number(startOrEndDate.value.substr(3, 2)) - 1,
  537. currentYear = startOrEndDate.value.substr(6, 4);
  538.  
  539. if (datePicker.style.display == 'inline-block' && datePicker.style.left == Math.floor(this.offsetLeft - datePicker.offsetWidth / 2) + 'px') {
  540. datePicker.style.display = 'none';
  541. return;
  542. }
  543. datePicker.style.display = 'inline-block';
  544.  
  545. datePicker.style.left = Math.floor(this.offsetLeft - (datePicker.offsetWidth / 2)) + 'px';
  546. datePicker.style.top = (this.offsetTop + 23) + 'px';
  547. month.innerHTML = monthNames[currentMonth] + '&nbsp;-&nbsp;' + currentYear;
  548.  
  549. //Change months
  550. document.querySelectorAll('#date-picker button')[0].onclick = function () {
  551. if (currentMonth > 0) {
  552. currentMonth -= 1;
  553. }
  554. else {
  555. currentMonth = 11;
  556. currentYear -= 1;
  557. }
  558. month.innerHTML = monthNames[currentMonth] + '&nbsp;-&nbsp;' + currentYear;
  559. generateDays(currentMonth, currentYear);
  560. }
  561.  
  562. document.querySelectorAll('#date-picker button')[1].onclick = function () {
  563. if (currentMonth < 11) {
  564. currentMonth += 1;
  565. }
  566. else {
  567. currentMonth = 0;
  568. currentYear += 1;
  569. }
  570. month.innerHTML = monthNames[currentMonth] + '&nbsp;-&nbsp;' + currentYear;
  571. generateDays(currentMonth, currentYear);
  572. }
  573.  
  574. //Click on day to pick date
  575. datePicker.onclick = function (ev) {
  576. var target = (typeof (event) != 'undefined') ? event.srcElement : ev.target;
  577.  
  578. if (target.className == 'active-day') {
  579. var inputMonth = (Number(currentMonth) + 1 > 9) ? Number(currentMonth) + 1 : 0 + '' + (Number(currentMonth) + 1),
  580. inputDay = (target.innerHTML > 9) ? target.innerHTML : 0 + '' + target.innerHTML;
  581. startOrEndDate.value = inputDay + '-' + inputMonth + '-' + currentYear;
  582. datePicker.style.display = 'none';
  583. }
  584. }
  585.  
  586. //Add days from current month, previous month (if current month starts from week day different from Sunday)
  587. //and next month (if there is empty space at the end of the last row with days)
  588. function generateDays(chosenMonth, chosenYear) {
  589. var activeMonth = new Date(chosenYear, chosenMonth),
  590. currentMonthDays = getDaysInMonth(chosenMonth, chosenYear).length,
  591. prevMonthDays = getDaysInMonth(chosenMonth - 1, chosenYear).length,
  592. wrapper = [],
  593. nextMonthDays = 0;
  594.  
  595. for (var z = 0; z < activeMonth.getDay() ; z++) {
  596. wrapper.push('<span class="inactive-day">' + ((prevMonthDays + 1) - (activeMonth.getDay() - z)) + '</span>');
  597. nextMonthDays++;
  598. }
  599. for (var i = 1; i <= currentMonthDays; i++) {
  600. wrapper.push('<span class="active-day">' + i + '</span>');
  601. nextMonthDays++;
  602. }
  603. lastDaysLength = (nextMonthDays <= 35) ? 35 : 42;
  604. lastDaysLength = ((nextMonthDays + activeMonth.getDay()) == 28) ? 28 : lastDaysLength;
  605. for (var h = 1; h <= lastDaysLength - nextMonthDays; h++) {
  606. wrapper.push('<span class="inactive-day">' + h + '</span>');
  607. }
  608. document.getElementById('date-picker-days').innerHTML = wrapper.join('');
  609. }
  610. generateDays(currentMonth, currentYear);
  611.  
  612. //Get the number of days in month
  613. function getDaysInMonth(month, year) {
  614. var month = month;
  615. if (month < 0) {
  616. month = 11;
  617. year -= year;
  618. }
  619. var date = new Date(year, month, 1),
  620. days = [];
  621. while (date.getMonth() === month) {
  622. days.push(new Date(date));
  623. date.setDate(date.getDate() + 1);
  624. }
  625. return days;
  626. }
  627.  
  628. document.onclick = function (ev) {
  629. var target = (typeof (event) != 'undefined') ? event.srcElement : ev.target;
  630. while (target) {
  631. if (target.id == 'date-picker' || target.className == 'open-date-picker') {
  632. return;
  633. };
  634. target = target.parentNode
  635. }
  636. datePicker.style.display = 'none';
  637. }
  638. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement