Advertisement
NikolayPaskulov

Untitled

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