Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var itemsList = {},
- clientsList = {},
- prevRow,
- prevCol = 0,
- tableHeader = document.getElementById('table-header'),
- docsWrapper = document.getElementById('docsWrapper'),
- mainWrapper = document.getElementById('main-wrapper'),
- firstDateInput = document.getElementById('firstDate'),
- clientSelect = document.getElementById('clientSelect'),
- storesSelect = document.getElementById('storesSelect'),
- secDateInput = document.getElementById('secDate'),
- checkBox = document.getElementById('checkBox'),
- clientsWithDocsBtn = document.getElementById('all-clients-with-docs'),
- table = document.getElementById('table'),
- storesList,
- motherShip = [],
- store = {};
- var r1 = ['objects', 'ЛЕЙДИ СОФИЯ АД'],
- r2 = ['items', 'ЛЕЙДИ СОФИЯ АД', '{"warehouse":"ОБЕКТИ:10 НЕСТАНДАРТНА ПРОДУКЦИЯ"}'];
- var storeIndex = 0;
- sendRequestToServer(JSON.stringify(r1), storesList);
- //sendRequestToServer('ГОТОВА ПРОДУКЦИЯ', 'store');
- function fillDocuments(store) {
- for (var i = 0; i < json.length; i++) {
- var len = Math.floor(Math.random() * 50) + 1;
- json[i].Items = [];
- for (var z = 0; z < len; z++) {
- var itemFromStore = Math.floor(Math.random() * store.length),
- itemCopy = {};
- for (var prop in store[itemFromStore]) {
- itemCopy[prop] = store[itemFromStore][prop];
- }
- itemCopy.quantity = Math.floor(Math.random() * 2) + 1;
- json[i].Items.push(itemCopy);
- }
- }
- }
- function sendRequestToServer(arr, v, check) {
- var request = new XMLHttpRequest();
- request.onreadystatechange = function () {
- if (request.readyState == 4 && request.status == 200) {
- if (v == storesList) {
- storesList = request.responseText;
- storesList = JSON.parse(storesList);
- fillStoresSelect(storesList);
- }
- if (v == 'store') {
- v = request.responseText;
- v = v.replace(/""/g, '"');
- v = reformatString(v, 0, 0);
- v = JSON.parse(v);
- fillDocuments(v);
- changeStore(v);
- if (check) {
- roundAllStores(motherShip);
- }
- }
- }
- }
- request.open("POST", "http://192.168.1.184:8000/pm", true);
- //request.open("POST", "http://127.0.0.1:8888/", true);
- request.send(arr);
- }
- function reformatString(str, indexA, indexB) {
- var right = str.match(/{/g),
- left = str.match(/}/g),
- newStr,
- isEdited = false;
- if (right.length == left.length) {
- return str;
- }
- if (str.lastIndexOf('{') > str.lastIndexOf('}')) {
- isEdited = true;
- newStr = str.slice(0, str.lastIndexOf(']')) + '}]';
- }
- if (str.lastIndexOf('}') == indexB) {
- return str
- }
- var firstIndexOfRight = str.indexOf('{', indexA),
- firstIndexOfLeft = str.indexOf('}', firstIndexOfRight + 1),
- nextIndexOfRight = str.indexOf('{', firstIndexOfRight + 1);
- if (nextIndexOfRight < firstIndexOfLeft) {
- if (str.lastIndexOf(':', nextIndexOfRight) < str.lastIndexOf(',', nextIndexOfRight)) {
- var lastIndexOfQ = str.lastIndexOf('"', nextIndexOfRight);
- newStr = str.slice(0, lastIndexOfQ + 1) + '}' + str.slice(lastIndexOfQ + 1);
- }
- } else if (!isEdited) {
- newStr = str;
- }
- isEdited = false;
- return reformatString(newStr, firstIndexOfRight + 1, firstIndexOfLeft);
- }
- function fillStoresSelect(arr) {
- strArray = ['<option style="display:none;">Избери склад</option><option>Всички</option>'];
- for (var i = 0; i < arr.length; i++) {
- strArray.push("<option value='" + '{"warehouse":' + '"' + arr[i] + '"}' + "'>" + arr[i].slice(arr[i].lastIndexOf(':') + 1) + "</option>");
- }
- storesSelect.innerHTML += strArray.join('');
- }
- storesSelect.onchange = function () {
- var selected = this.value;
- if (selected == 'Всички') {
- motherShip = [];
- var intervalCounter = 2;
- var selectOptions = this.getElementsByTagName('option');
- var interval = setInterval(intervalStart, 100);
- } else {
- sendRequestToServer(JSON.stringify(['items', 'ЛЕЙДИ СОФИЯ АД', selected]), 'store');
- }
- function intervalStart() {
- console.log(selectOptions[intervalCounter].value);
- sendRequestToServer(JSON.stringify(['items', 'ЛЕЙДИ СОФИЯ АД', selectOptions[intervalCounter].value]), 'store');
- if (selectOptions.length - 2 == intervalCounter) {
- intervalEnd();
- }
- intervalCounter++;
- }
- function intervalEnd() {
- sendRequestToServer(JSON.stringify(['items', 'ЛЕЙДИ СОФИЯ АД', selectOptions[intervalCounter].value]), 'store', true);
- clearInterval(interval);
- }
- }
- function roundAllStores(arr) {
- store = arr[0];
- for (var i = 1; i < arr.length; i++) {
- for (var key in arr[i]) {
- if (store[key]) {
- if (arr[i][key].quantity) {
- store[key].quantity = Number(store[key].quantity) + Number(arr[i][key].quantity);
- } else {
- store[key].quantity = 0;
- }
- } else {
- store[key] = {};
- if (arr[i][key].quantity) {
- store[key].quantity = Number(arr[i][key].quantity);
- } else {
- store[key].quantity = 0;
- }
- }
- }
- }
- }
- //Extract all items and clients from the main JSON and put them into two associative arrays
- function generateRef(obj) {
- for (var a = 0; a < obj.length; a++) {
- var currentDate = obj[a].date;
- if (checkIfDateIsValid(currentDate.slice(6, currentDate.length), currentDate.slice(4, 6), currentDate.slice(0, 4))) {
- fillclientsList(obj[a].partner, obj[a]);
- for (var b = 0; b < obj[a].Items.length; b++) {
- checkItems(obj[a].partner, obj[a].Items[b]);
- }
- }
- }
- }
- //Convert store JSON into an object
- function changeStore(currentStore) {
- store = {};
- for (var i = 0; i < currentStore.length; i++) {
- store[currentStore[i].name] = currentStore[i];
- }
- motherShip.push(store);
- }
- //on every merchandise if array fill clients that have it with whole quantity
- function checkItems(client, march) {
- var client = client.slice(client.lastIndexOf(':') + 1);
- if (itemsList[march.name]) {
- if (itemsList[march.name][client]) {
- itemsList[march.name][client] = Number(itemsList[march.name][client]) + Number(march.quantity);
- } else {
- itemsList[march.name][client] = Number(march.quantity);
- }
- } else if (march.name) {
- itemsList[march.name] = {};
- itemsList[march.name][client] = Number(march.quantity);
- }
- }
- //all clients with theys documents and full info on document
- function fillclientsList(name, obj) {
- var Items = {},
- name = name.slice(name.lastIndexOf(':') + 1);
- if (clientsList[name]) {
- if (clientsList[name][obj.docNumber]) {
- return;
- } else {
- clientsList[name][obj.docNumber] = {
- date: obj.date,
- };
- }
- } else {
- clientsList[name] = {};
- clientsList[name][obj.docNumber] = {
- date: obj.date,
- };
- }
- for (var i = 0; i < obj.Items.length; i++) {
- if (Items[obj.Items[i].name]) {
- Items[obj.Items[i].name].quantity += Number(obj.Items[i].quantity);
- } else {
- Items[obj.Items[i].name] = {};
- Items[obj.Items[i].name].quantity = Number(obj.Items[i].quantity);
- }
- }
- clientsList[name][obj.docNumber]['Items'] = Items;
- }
- function buildTable(reUse) {
- (function fillHeader() {
- var strArray = ['<div class="table-row"><div class="plain-cell"> </div><div class="plain-cell">No</div>'],
- docArr = ['<div class="table-row"><div class="plain-cell">Док. номер</div><div class="plain-cell"> </div>'],
- docDate = ['<div class="table-row"><div class="plain-cell">Док. дата</div><div class="plain-cell"> </div>'];
- for (var key in clientsList) {
- if (reUse) {
- for (var prop in clientsList[key]) {
- var date = clientsList[key][prop].date;
- strArray.push('<div class="plain-cell no-print">' + key + '</div>')
- docArr.push('<div class="plain-cell">' + prop + '</div>');
- docDate.push('<div class="plain-cell">' + date.substr(6, 2) + '.' + date.substr(4, 2) + '.' + date.substr(0, 4) + '</div>');
- }
- }
- else {
- strArray.push('<div class="plain-cell no-print">' + key + '</div>');
- }
- }
- docArr.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div></div>')
- docDate.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div></div>')
- strArray.push('<div class="plain-cell">Общо планирани</div><div class="plain-cell">Количество от склад</div><div class="plain-cell">Блокирани</div><div class="plain-cell">Разлика</div></div>');
- if (reUse) {
- docsWrapper.innerHTML = docArr.join('') + docDate.join('');
- }
- tableHeader.innerHTML = strArray.join('');
- resizeConteiners(tableHeader.children[0].children.length * 100 + 300);
- }());
- (function fillRows() {
- var strArray = [],
- counter = 1,
- totalRowItems = 0;
- for (var key in itemsList) {
- strArray.push('<div class="table-row"><div class="plain-cell">' + key + '</div><div class="plain-cell">' + counter + '</div>')
- for (var name in clientsList) {
- if (reUse) {
- var result = expandedRows(clientsList[name], key);
- strArray.push(result.html);
- totalRowItems += result.quantity;
- continue;
- }
- if (itemsList[key][name]) {
- strArray.push('<div class="plain-cell no-print">' + itemsList[key][name] + '</div>')
- totalRowItems += Number(itemsList[key][name]);
- } else {
- strArray.push('<div class="plain-cell no-print"> </div>')
- }
- }
- var storeQuantity = (typeof (store[key].quantity) == 'undefined') ? 0 : store[key].quantity,
- storeBlocked = (typeof (store[key].blocked) != 'undefined') ? store[key].blocked : 0;
- quantitydifference = Number(storeQuantity) - storeBlocked - totalRowItems;
- strArray.push('<div class="plain-cell">' + totalRowItems + '</div><div class="plain-cell">' + storeQuantity + '</div>' +
- '<div class="plain-cell">' + storeBlocked + '</div>' +
- '<div class="plain-cell">' + quantitydifference + '</div></div>');
- counter++;
- totalRowItems = 0;
- }
- if (reUse) {
- table.innerHTML = setSerialNumberRow(clientsList, true);
- }
- else {
- table.innerHTML = setSerialNumberRow(clientsList, false);
- }
- table.innerHTML += strArray.join('');
- printTotalQuantity();
- }());
- }
- //Build row with serial number for each client or document
- function setSerialNumberRow(obj, isExpanded) {
- var strArr = [],
- prevProp,
- counter = 1;
- strArr.push('<div class="table-row no-print"><div class="plain-cell"> </div><div class="plain-cell">No</div>');
- for (var prop in obj) {
- strArr.push('<div class="plain-cell">' + counter + '</div>');
- counter++;
- if (isExpanded) {
- var countKeys = 0;
- for (var key in obj[prop]) {
- countKeys++;
- }
- for (var i = 0; i < countKeys - 1; i++) {
- strArr.push('<div class="plain-cell"> </div>');
- }
- }
- prevProp = prop;
- }
- strArr.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div>');
- return strArr.join('');
- }
- //expands basic table after click on chechbox
- function expandedRows(obj, itemName) {
- var strArray = [];
- totalRowItems = 0;
- for (var key in obj) {
- if (obj[key].Items[itemName]) {
- strArray.push('<div class="plain-cell no-print">' + obj[key].Items[itemName].quantity + '</div>');
- totalRowItems += Number(obj[key].Items[itemName].quantity);
- } else {
- strArray.push('<div class="plain-cell no-print"> </div>');
- }
- }
- return {
- html: strArray.join(''),
- quantity: totalRowItems
- }
- }
- //Visualize all documents from client chosen by click on the header
- tableHeader.onclick = function (e) {
- var target = (typeof (event) != 'undefined') ? event.srcElement.outerText : e.target.innerHTML,
- checkBiggerWidth = 0;
- if (target == 'No' || target == 'Общо планирани' || target == 'Количество от склад' ||
- target == 'Блокирани' || target == 'Разлика' || target == '') {
- return;
- }
- if (target == 'Всички') {
- clientsWithDocsBtn.disabled = false;
- clientsWithDocsBtn.checked = false;
- if (!checkBox.checked) {
- checkBox.click();
- }
- docsWrapper.style.display = 'none';
- buildTable();
- return;
- }
- docsWrapper.style.display = '';
- changeHeaderAfterClick(target);
- clientsWithDocsBtn.disabled = true;
- resizeConteiners(docsWrapper.childNodes[0].children.length * 100 + 300)
- };
- //after click on some cell change color of a cell row and col
- table.onclick = function (ev) {
- var target = (typeof (event) != 'undefined') ? event.srcElement : ev.target;
- if (target.className == 'plain-cell no-print') {
- var rows = document.querySelectorAll('#table .table-row');
- if (prevCol <= rows[0].children.length) {
- for (var z = 0; z < rows.length; z++) {
- rows[z].children[prevCol].style.backgroundColor = '';
- }
- }
- if (prevCol == Array.prototype.indexOf.call(target.parentNode.childNodes, target) && prevRow == target.parentNode) {
- prevRow.style.backgroundColor = '';
- prevCol = 0;
- return;
- }
- prevCol = Array.prototype.indexOf.call(target.parentNode.childNodes, target);
- for (var z = 0; z < rows.length; z++) {
- rows[z].children[prevCol].style.backgroundColor = 'lightBlue';
- }
- if (prevRow) {
- prevRow.style.backgroundColor = '';
- }
- prevRow = target.parentNode;
- prevRow.style.backgroundColor = 'lightblue';
- target.style.backgroundColor = '#bde0eb';
- }
- };
- //fill table with data for clicked client
- function fillTableAfterClick(targetName) {
- var strArray = [],
- invoiceNumber = [],
- invoiceDate = [],
- rowCounter = 1,
- iterationCounter = 0,
- countRowItems = 0;
- invoiceNumber.push('<div class="table-row no-print"><div class="plain-cell">Док.ном</div><div class="plain-cell"> </div>')
- invoiceDate.push('<div class="table-row no-print"><div class="plain-cell">Дата</div><div class="plain-cell"> </div>')
- var itemsArr = extractItemsFromClient(clientsList[targetName]);
- for (var name in itemsArr) {
- strArray.push('<div class="table-row"><div class="plain-cell">' + name + '</div><div class="plain-cell">' + rowCounter + '</div>');
- var clientKeys = 0;
- for (var keys in clientsList[targetName]) {
- clientKeys++;
- }
- for (var key in clientsList[targetName]) {
- if (iterationCounter < clientKeys) {
- var currentDate = clientsList[targetName][key].date;
- invoiceNumber.push('<div class="plain-cell">' + key + '</div>')
- invoiceDate.push('<div class="plain-cell">' + currentDate.slice(6, currentDate.length) + '.' + currentDate.slice(4, 6) + '.' + currentDate.slice(0, 4) + '</div>')
- }
- if (clientsList[targetName][key].Items[name]) {
- strArray.push('<div class="plain-cell no-print">' + clientsList[targetName][key].Items[name].quantity + '</div>');
- countRowItems += Number(clientsList[targetName][key].Items[name].quantity);
- } else {
- strArray.push('<div class="plain-cell no-print"> </div>');
- }
- iterationCounter++;
- }
- var storeQuantity = (store[name].quantity != undefined) ? store[name].quantity : 0,
- quantitydifference = Number(storeQuantity) - 0 - countRowItems;
- strArray.push('<div class="plain-cell">' + countRowItems + '</div><div class="plain-cell">' + storeQuantity + '</div>' +
- '<div class="plain-cell">' + 0 + '</div><div class="plain-cell">' + quantitydifference + '</div>');
- strArray.push('</div>');
- countRowItems = 0;
- rowCounter++;
- }
- invoiceNumber.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div>')
- invoiceDate.push('<div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div><div class="plain-cell"> </div></div>')
- docsWrapper.innerHTML = invoiceNumber.join('') + invoiceDate.join('');
- table.innerHTML = setSerialNumberRow(clientsList[targetName], false) + strArray.join('');
- printTotalQuantity();
- }
- //fill footer with calculated data from colums
- function printTotalQuantity() {
- var strArray = ['<div class="table-row"><div class="plain-cell">Общо</div><div class="plain-cell"> </div>'],
- sum = 0;
- for (var i = 2; i < table.children[0].children.length; i++) {
- for (var z = 1; z < table.children.length - 1; z++) {
- sum += Number(table.children[z].children[i].innerHTML == ' ' ? '' : table.children[z].children[i].innerHTML);
- }
- if (i < table.children[0].children.length - 4) {
- strArray.push('<div class="plain-cell no-print">' + sum + '</div>')
- }
- else {
- strArray.push('<div class="plain-cell">' + sum + '</div>')
- }
- sum = 0;
- }
- strArray.push('</div>');
- table.innerHTML += strArray.join('');
- }
- //extract only items that are in all clients
- function extractItemsFromClient(client) {
- var result = {};
- for (var doc in client) {
- for (var item in client[doc].Items) {
- if (!result[item]) result[item] = {};
- }
- }
- return result;
- }
- document.getElementById('show-reference').onclick = checkIfDatesInputAreActive;
- function fillSelectWithClients() {
- var strArray = [];
- if (firstDateInput.value && secDateInput.value) {
- strArray.push('<option>Всички</option>');
- itemsList = {};
- clientsList = {};
- generateRef(json);
- for (var name in clientsList) {
- strArray.push('<option>' + name + '</option>');
- }
- }
- clientSelect.innerHTML = strArray.join('');
- }
- //change header with only clicked client name and empty cells; call fillTableAfterClick with client name
- function changeHeaderAfterClick(name) {
- tableHeader.innerHTML = '<div class="table-row"><div class="plain-cell"> </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>' +
- '<div class="plain-cell">Количество от склад</div><div class="plain-cell">Блокирани</div><div class="plain-cell">Разлика</div></div>';
- fillTableAfterClick(name);
- clientsWithDocsBtn.checked = true;
- clientsWithDocsBtn.disabled = true;
- tableHeader.childNodes[0].firstChild.innerHTML = 'Всички';
- }
- function checkIfDatesInputAreActive() {
- var clientSelectValue = clientSelect.options[clientSelect.selectedIndex].value;
- if (firstDateInput.value && secDateInput.value) {
- checkBox.disabled = false;
- if (clientSelectValue != 'Всички') {
- docsWrapper.style.display = '';
- changeHeaderAfterClick(clientSelectValue);
- if (!checkBox.checked) {
- checkBox.click();
- }
- resizeConteiners(docsWrapper.children[0].children.length * 100 + 300)
- return;
- }
- clientsList = {};
- itemsList = {};
- generateRef(json);
- if (!checkBox.checked) {
- checkBox.click();
- }
- if (clientsWithDocsBtn.disabled) {
- clientsWithDocsBtn.disabled = false;
- }
- if (clientsWithDocsBtn.checked) {
- clientsWithDocsBtn.checked = false;
- }
- docsWrapper.style.display = 'none';
- buildTable();
- }
- }
- //find only dates that are in range
- function checkIfDateIsValid(day, month, year) {
- var firstDateInput = document.getElementById('firstDate'),
- secDateInput = document.getElementById('secDate'),
- regEx = /[0-9]+/g,
- firstDateArray,
- secDateArray;
- firstDateArray = firstDateInput.value.match(regEx);
- secDateArray = secDateInput.value.match(regEx);
- if (firstDateArray && secDateArray) {
- var prevDate = new Date(firstDateArray[2], (firstDateArray[1] - 1), firstDateArray[0], 0, 0, 0, 0);
- var currentDate = new Date(secDateArray[2], (secDateArray[1] - 1), secDateArray[0], 0, 0, 0, 0);
- if (prevDate > currentDate) {
- return;
- }
- var productDate = new Date(year, (Number(month) - 1), Number(day), 0, 0, 0, 0);
- if (productDate.valueOf() >= prevDate.valueOf() && productDate.valueOf() <= currentDate.valueOf()) {
- return true;
- } else {
- return false;
- }
- }
- }
- checkBox.onclick = function () {
- if (!this.checked) {
- document.head.innerHTML += '<style>.no-print{display:none}</style>';
- resizeConteiners(table.offsetWidth);
- docsWrapper.style.display = 'none';
- }
- else {
- document.head.removeChild(document.querySelectorAll('style')[0]);
- resizeConteiners(table.children[0].children.length * 100 + 300);
- if (clientsWithDocsBtn.checked) {
- docsWrapper.style.display = '';
- } else {
- docsWrapper.style.display = 'none';
- }
- }
- if (prevRow) {
- prevRow.style.backgroundColor = '';
- }
- };
- clientsWithDocsBtn.onclick = function () {
- if (this.checked) {
- buildTable(true)
- docsWrapper.style.display = '';
- if (!checkBox.checked) checkBox.click();
- }
- else {
- buildTable();
- resizeConteiners(table.offsetWidth);
- docsWrapper.style.display = 'none';
- }
- };
- function resizeConteiners(size) {
- docsWrapper.style.width = size + 'px';
- mainWrapper.style.width = size + 2 + 'px';
- tableHeader.childNodes[0].style.width = size + 'px';
- if (docsWrapper.children.length == 0) {
- return;
- }
- if (!document.getElementById('empty-cell')) {
- return;
- }
- document.getElementById('empty-cell').style.width = (docsWrapper.offsetWidth - 1000) + 'px';
- if (docsWrapper.children[0].children.length <= 7) {
- document.getElementById('empty-cell').style.display = 'none'
- }
- }
- var datePickerBtns = document.querySelectorAll('.open-date-picker');
- for (var i = 0; i < datePickerBtns.length; i++) {
- datePickerBtns[i].onclick = generateDateForm;
- }
- var prevDate;
- function generateDateForm(ev) {
- var datePicker = document.getElementById('date-picker');
- //Set the main structure of the date-picker element;
- datePicker.innerHTML = '<div><button>◄</button><span></span><button>►</button></div><span class="hor-line"></span><div id="date-picker-week"><span>Sun</span>' +
- '<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>';
- var monthNames = ["January", "February", "March", "April", "May", "June",
- "July", "August", "September", "October", "November", "December"],
- month = datePicker.querySelectorAll('span')[0],
- currentMonth = (prevDate) ? prevDate.getMonth() : new Date().getMonth(),
- currentYear = (prevDate) ? prevDate.getFullYear() : new Date().getFullYear(),
- startOrEndDate = this.previousSibling,
- opacityVal = 0,
- hideCalendar;
- function hideDatePicker() {
- if (opacityVal == 9) {
- datePicker.style.opacity = 0;
- clearInterval(hideCalendar);
- datePicker.style.display = 'none';
- opacityVal = 0;
- }
- else {
- datePicker.style.opacity = '0.' + (9 - opacityVal);
- opacityVal++;
- }
- }
- if (datePicker.style.display == 'inline-block' && datePicker.style.left == Math.floor(this.offsetLeft - datePicker.offsetWidth / 2) + 'px') {
- hideCalendar = setInterval(hideDatePicker, 10);
- return;
- }
- datePicker.style.display = 'inline-block';
- datePicker.style.opacity = '0';
- var showCalendar = setInterval(function () {
- opacityVal++;
- if (opacityVal == 10) {
- datePicker.style.opacity = 1;
- clearInterval(showCalendar);
- opacityVal = 0;
- }
- else {
- datePicker.style.opacity = '0.' + opacityVal;
- }
- }, 10);
- datePicker.style.left = Math.floor(this.offsetLeft - (datePicker.offsetWidth / 2)) + 'px';
- datePicker.style.top = (this.offsetTop + 23) + 'px';
- month.innerHTML = monthNames[currentMonth] + ' - ' + currentYear;
- //Change months
- document.querySelectorAll('#date-picker button')[0].onclick = function () {
- if (currentMonth > 0) {
- currentMonth -= 1;
- }
- else {
- currentMonth = 11;
- currentYear -= 1;
- }
- month.innerHTML = monthNames[currentMonth] + ' - ' + currentYear;
- generateDays(currentMonth, currentYear);
- }
- document.querySelectorAll('#date-picker button')[1].onclick = function () {
- if (currentMonth < 11) {
- currentMonth += 1;
- }
- else {
- currentMonth = 0;
- currentYear += 1;
- }
- month.innerHTML = monthNames[currentMonth] + ' - ' + currentYear;
- generateDays(currentMonth, currentYear);
- }
- //Click on day to pick date
- datePicker.onclick = function (ev) {
- var target = (typeof (event) != 'undefined') ? event.srcElement : ev.target,
- inputMonth = (Number(currentMonth) + 1 > 9) ? Number(currentMonth) + 1 : 0 + '' + (Number(currentMonth) + 1),
- inputDay = (target.innerHTML > 9) ? target.innerHTML : 0 + '' + target.innerHTML;
- if (target.parentNode.id == 'date-picker-days' && target.className != 'inactive-day') {
- startOrEndDate.value = inputDay + '-' + inputMonth + '-' + currentYear;
- datePicker.style.display = 'none';
- prevDate = new Date(currentYear, currentMonth);
- }
- }
- //Add days from current month, previous month (if current month starts from week day different from Sunday)
- //and next month (if there is empty space at the end of the last row with days)
- function generateDays(chosenMonth, chosenYear) {
- var activeMonth = new Date(chosenYear, chosenMonth),
- currentMonthDays = getDaysInMonth(chosenMonth, chosenYear).length,
- prevMonthDays = getDaysInMonth(chosenMonth - 1, chosenYear).length,
- wrapper = [],
- nextMonthDays = 0;
- for (var z = 0; z < activeMonth.getDay() ; z++) {
- wrapper.push('<span class="inactive-day">' + ((prevMonthDays + 1) - (activeMonth.getDay() - z)) + '</span>');
- nextMonthDays++;
- }
- for (var i = 1; i <= currentMonthDays; i++) {
- wrapper.push('<span class="active-day">' + i + '</span>');
- nextMonthDays++;
- }
- lastDaysLength = (nextMonthDays <= 35) ? 35 : 42;
- lastDaysLength = ((nextMonthDays + activeMonth.getDay()) == 28) ? 28 : lastDaysLength;
- for (var h = 1; h <= lastDaysLength - nextMonthDays; h++) {
- wrapper.push('<span class="inactive-day">' + h + '</span>');
- }
- document.getElementById('date-picker-days').innerHTML = wrapper.join('');
- }
- generateDays(currentMonth, currentYear);
- //Get the number of days in month
- function getDaysInMonth(month, year) {
- var month = month;
- if (month < 0) {
- month = 11;
- year -= year;
- }
- var date = new Date(year, month, 1),
- days = [];
- while (date.getMonth() === month) {
- days.push(new Date(date));
- date.setDate(date.getDate() + 1);
- }
- return days;
- }
- document.onclick = function (ev) {
- var target = (typeof (event) != 'undefined') ? event.srcElement : ev.target;
- while (target) {
- if (target.id == 'date-picker' || target.className == 'open-date-picker') {
- return;
- };
- target = target.parentNode
- }
- hideCalendar = setInterval(hideDatePicker, 10);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement