Advertisement
NikolayPaskulov

Untitled

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