Advertisement
NikolayPaskulov

Untitled

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