Guest User

Untitled

a guest
Mar 6th, 2017
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. /**
  3.  *
  4.  * TODO
  5.  * [R E F A C T O R          P L E A S E]
  6.  *
  7.  */
  8.  
  9.  
  10. // APP START
  11. var ua = navigator.userAgent.toLowerCase();
  12. alert(ua);
  13. var isAndroid = ua.indexOf("android") > -1;
  14. var isChrome_bad = /chrom(e|ium)/.test(ua.toLowerCase());
  15. var isNative = ((ua.indexOf('mozilla/5.0') > -1 && ua.indexOf('android ') > -1 && ua.indexOf('applewebkit') > -1) && (ua.indexOf('version') > -1));
  16. var isChrome = !!window.chrome;
  17.  
  18. // window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
  19. // window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction || {READ_WRITE: "readwrite"};
  20. // window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
  21.  
  22. // alert('window.indexedDB: ' + window.indexedDB);
  23. // alert('window.IDBTransaction: ' + window.IDBTransaction);
  24. // alert('type of window.IDBKeyRange =  ' + typeof IDBKeyRange);
  25.  
  26. alert('Version: 0.8');
  27.  
  28. function checkCamera() {
  29.     return new Promise(function (fullfill, reject) {
  30.         var preview = document.getElementById('CHECK-video');
  31.         var canvas = document.getElementById('CHECK-canvas');
  32.         var result = false;
  33.  
  34.         $('#CHECK-canvas').attr('width', 150);
  35.         $('#CHECK-canvas').attr('height', 150);
  36.  
  37.         var context = canvas.getContext('2d');
  38.  
  39.         function GetPixel(x, y) {
  40.             var p = context.getImageData(x, y, 1, 1).data;
  41.             var hex = "#" + ("000000" + rgbToHex(p[0], p[1], p[2])).slice(-6);
  42.             return hex;
  43.         }
  44.  
  45.         function rgbToHex(r, g, b) {
  46.             if (r > 255 || g > 255 || b > 255)
  47.                 throw "Invalid color component";
  48.             return ((r << 16) | (g << 8) | b).toString(16);
  49.         }
  50.  
  51.         setTimeout(function () {
  52.             context.drawImage(preview, 0, 0, 150, 150);
  53.             var dataURL = canvas.toDataURL('image/jpeg', 0.5);
  54.  
  55.             var checkers = {
  56.                 LT: GetPixel(2, 2),
  57.                 RT: GetPixel(148, 2),
  58.                 CC: GetPixel(75, 75),
  59.                 LB: GetPixel(2, 148),
  60.                 RB: GetPixel(148, 148)
  61.             }
  62.  
  63.             for (var key in checkers) {
  64.                 var value = checkers[key];
  65.                 if (value !== '#000000') fullfill(true);
  66.             }
  67.  
  68.             setTimeout(function () {
  69.                 fullfill(false);
  70.             }, 1000);
  71.         }, 2000);
  72.  
  73.         var devicesStore = [];
  74.         function gotDevices(deviceInfos) {
  75.             for (var i = 0; i !== deviceInfos.length; ++i) {
  76.                 var deviceInfo = deviceInfos[i];
  77.                 var deviceObj = {};
  78.  
  79.                 deviceObj = { id: deviceInfo.deviceId, label: deviceInfo.label };
  80.                 devicesStore.push(deviceObj);
  81.             }
  82.         }
  83.  
  84.         navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
  85.  
  86.         function gotStream(stream) {
  87.             window.stream = stream;
  88.             preview.srcObject = stream;
  89.             return navigator.mediaDevices.enumerateDevices();
  90.         }
  91.  
  92.         function start() {
  93.             if (window.stream) {
  94.                 window.stream.getTracks().forEach(function (track) {
  95.                     track.stop();
  96.                 });
  97.             }
  98.  
  99.             var constraints = {
  100.                 audio: false,
  101.                 video: true,
  102.             };
  103.  
  104.             navigator.mediaDevices.getUserMedia(constraints).
  105.                 then(gotStream).catch(handleError);
  106.         }
  107.  
  108.         function handleError(error) {
  109.             console.log('navigator.getUserMedia error: ', error);
  110.         }
  111.  
  112.  
  113.         start();
  114.     });
  115. }
  116.  
  117.  
  118. var app = {
  119.     store: {
  120.         logged: { remember: false, currentUser: '', token: null },
  121.         activeSessions: [],
  122.         currentSession: {},
  123.         cameraEnable: null,
  124.         showSplash: null
  125.     },
  126.  
  127.     currentSessionId: null,
  128.     defaultEmail: 'Rating@ButyBOOK.cz'
  129. };
  130.  
  131. app.setRemember = function (r) {
  132.     this.store.logged.remember = r;
  133. }
  134.  
  135. app.generateId = function () {
  136.     return '' + Math.random() * (100000 - 1) + 1 + '';
  137. }
  138.  
  139. app.loadData = function () {
  140.     var self = this;
  141.     self.store = JSON.parse(localStorage.getItem('watcutData'));
  142. }
  143.  
  144. app.saveData = function () {
  145.     var self = this;
  146.     setTimeout(function () {
  147.         localStorage.setItem('watcutData', JSON.stringify(self.store));
  148.     }, 100)
  149. }
  150.  
  151. app.addSession = function (session) {
  152.     var copyStore = this.store.activeSessions;
  153.     copyStore.push(session);
  154.  
  155.     this.store.activeSessions = copyStore;
  156.     this.saveData();
  157. }
  158.  
  159. app.setCurrentSession = function (sesssion) {
  160.     this.store.currentSession = sesssion;
  161.     this.saveData();
  162. }
  163.  
  164. app.removeSessionByIdV2 = function (id) {
  165.     return db.sessions.where('id').equals(id).delete();
  166. }
  167.  
  168. app.logout = function () {
  169.     this.store.logged.token = null;
  170.     this.store.logged.currentUser = null;
  171.     this.saveData();
  172. }
  173.  
  174. app.setToken = function (token) {
  175.     this.store.logged.token = token;
  176.     this.saveData();
  177. }
  178.  
  179. app.setCurrentUser = function (email) {
  180.     this.store.logged.currentUser = email;
  181. }
  182.  
  183. app.getSessionFromDB = function (id) {
  184.     return db.sessions.get(id);
  185. }
  186.  
  187. app.saveToDB = function (session) {
  188.     return db.sessions.put(session);
  189. }
  190.  
  191. app.togglePhotoSelectedV2 = function (photoId, state) {
  192.     var $this = this,
  193.         sessionId = $this.currentSessionId;
  194.  
  195.     return $this.getSessionFromDB(sessionId).then(function (session) {
  196.         var photos = session.photos;
  197.         if (photos.length > 0) {
  198.             photos.forEach(function (phItem, index, photos) {
  199.                 if (phItem.id === photoId) phItem.selected = state;
  200.                 $this.updatePhotosInSession(sessionId, photos);
  201.             });
  202.         }
  203.     });
  204. }
  205.  
  206. app.removePhotoByIdV2 = function (id) {
  207.     var $this = this,
  208.         sessionId = $this.currentSessionId;
  209.  
  210.     $this.getSessionFromDB(sessionId).then(function (session) {
  211.         var photos = session.photos;
  212.  
  213.         if (photos.length > 0) {
  214.             photos.forEach(function (item, index) {
  215.                 if (item != null && item.id === id && item.id != session.cover) {
  216.                     photos.splice(index, 1);
  217.  
  218.                     $this.updatePhotosInSession(sessionId, photos).then(function (u) {
  219.                         if (u == 1) $('ons-list-item[data-photo-id="' + id + '"]').remove();
  220.                         else alert('Error. Try to again.');
  221.                     })
  222.                 }
  223.             });
  224.         }
  225.     });
  226. }
  227.  
  228. app.rotatePhotoById = function (id) {
  229.     var $this = this,
  230.         sessionId = $this.currentSessionId;
  231.  
  232.     $this.getSessionFromDB(sessionId).then(function (session) {
  233.         var photos = session.photos;
  234.  
  235.         if (photos.length > 0) {
  236.             photos.forEach(function (item, index) {
  237.                 if (item != null && item.id === id) {
  238.                     var canvas = document.getElementById("rotate-edit"),
  239.                         ctx = canvas.getContext("2d"),
  240.                         img = new Image();
  241.  
  242.                     item.angle += 90;
  243.                     if (item.angle == 360) item.angle = 0;
  244.  
  245.                     img.onload = function () {
  246.                         var cache = this;
  247.  
  248.                         canvas.width = cache.width; //double the canvas width
  249.                         canvas.height = cache.height; //double the canvas height
  250.  
  251.                         ctx.save();
  252.                         ctx.clearRect(0, 0, canvas.width, canvas.height); //clear the canvas
  253.                         ctx.translate(cache.width / 2, cache.height / 2); //let's translate
  254.                         ctx.rotate(90 * Math.PI / 180); //increment the angle and rotate the image
  255.                         ctx.drawImage(img, -cache.width / 2, -cache.height / 2, cache.width, cache.height); //draw the image ;)
  256.                         ctx.restore(); //restore the state of canvas
  257.  
  258.                         var b64 = canvas.toDataURL("image/jpeg");
  259.                         photos[index].base64 = b64;
  260.                         photos[index].angle = item.angle;
  261.  
  262.                         $this.updatePhotosInSession(sessionId, photos).then(function () {
  263.                             $('ons-list-item[data-photo-id="' + item.id + '"]').css('background-image', 'url(' + b64 + ')');
  264.                         });
  265.                     }
  266.  
  267.                     img.src = item.base64;
  268.                 }
  269.             });
  270.         }
  271.     });
  272. }
  273.  
  274. app.sendData = function (id, fSuccess, fError) {
  275.     self = this;
  276.     this.getSessionFromDB(id).then(function (session) {
  277.         var link = 'https://butybook.cz/wp-json/wp/v1/haircut',
  278.             currentSession = session;
  279.  
  280.         console.log(currentSession);
  281.  
  282.         var dataToSend = {
  283.             id: currentSession.id,
  284.             title: currentSession.title,
  285.             content: '',
  286.             specials: parseInt(currentSession.specials),
  287.             color: parseInt(currentSession.color),
  288.             cut: parseInt(currentSession.cut),
  289.             gender: parseInt(currentSession.gender),
  290.             type: parseInt(currentSession.type),
  291.             coloration: parseInt(currentSession.coloration),
  292.             email: currentSession.email,
  293.             status: 'publish'
  294.         };
  295.  
  296.         var data = new FormData();
  297.         data.append('title', dataToSend.title);
  298.         data.append('content', dataToSend.content);
  299.         data.append('specials', data.specials);
  300.         data.append('color', dataToSend.color);
  301.         data.append('cut', dataToSend.cut);
  302.         data.append('gender', dataToSend.gender);
  303.         data.append('type', dataToSend.type);
  304.         data.append('coloration', dataToSend.coloration);
  305.         data.append('status', dataToSend.status);
  306.         data.append('email', dataToSend.email);
  307.  
  308.         console.log(data);
  309.  
  310.         var xhr = new XMLHttpRequest();
  311.  
  312.         xhr.addEventListener('readystatechange', function () {
  313.             if (this.readyState === 4) {
  314.                 console.log('STATUS: ' + this.status);
  315.                 if (this.status === 201) {
  316.                     app.removePhotoByIdV2(id);
  317.                     var response = this.responseText;
  318.                     console.log(response);
  319.  
  320.                     var id = JSON.parse(response).id;
  321.                     console.log('Response ID = ' + id);
  322.  
  323.                     if (dataToSend.email !== self.defaultEmail && dataToSend !== '' && dataToSend !== null) {
  324.                         self.createUser(id, dataToSend.email);
  325.                     }
  326.  
  327.                     self.sendMedia(id, currentSession, fSuccess, fError);
  328.                 } else {
  329.                     fError(this.statusText);
  330.                 }
  331.             }
  332.         });
  333.  
  334.         xhr.open('POST', 'https://butybook.cz/wp-json/wp/v2/haircut');
  335.         xhr.setRequestHeader('authorization', 'Bearer ' + self.store.logged.token);
  336.  
  337.         xhr.send(data);
  338.     });
  339. }
  340.  
  341. app.createUser = function (id, email) {
  342.     var createUserData = new FormData();
  343.     createUserData.append('customer_email', email);
  344.  
  345.  
  346.     var xhr = new XMLHttpRequest();
  347.     xhr.addEventListener('readystatechange', function () {
  348.         if (this.readyState === 4) {
  349.             console.log('app.createUser STATUS: ' + this.status);
  350.             if (this.status === 201 || this.status === 200) {
  351.                 console.log(this.responseText);
  352.             }
  353.         }
  354.     });
  355.  
  356.     xhr.open('POST', 'https://butybook.cz/wp-json/wp/v2/haircut/' + id);
  357.     xhr.setRequestHeader('authorization', 'Bearer ' + self.store.logged.token);
  358.  
  359.     xhr.send(createUserData);
  360. }
  361.  
  362. app.sendMedia = function (id, session, fSuccess, fError) {
  363.     var self = this;
  364.  
  365.     var coverId = session.cover;
  366.     var photos = session.photos;
  367.  
  368.     photos.forEach(function (item, index, photos) {
  369.         if (item.selected || item.id === coverId) {
  370.             var data = new FormData(),
  371.                 fileData = dataURLtoBlob(item.base64);
  372.  
  373.             data.append('post', id);
  374.             data.append('file', fileData, id + '-photo-' + index + '.jpg');
  375.             data.append('featured', (item.id == coverId ? '1' : '0'));
  376.  
  377.             var xhr = new XMLHttpRequest();
  378.  
  379.             xhr.addEventListener('readystatechange', function () {
  380.                 if (this.readyState === 4) {
  381.                     if (this.status === 201) {
  382.                         console.log('Successfully uploded image');
  383.                         fSuccess();
  384.                     } else {
  385.                         fError(this.statusText);
  386.                     }
  387.                 }
  388.             });
  389.  
  390.             xhr.open('POST', 'https://butybook.cz/wp-json/wp/v2/media');
  391.             xhr.setRequestHeader('authorization', 'Bearer ' + self.store.logged.token);
  392.  
  393.             xhr.send(data);
  394.         }
  395.     });
  396. }
  397.  
  398. app.getCoverV2 = function (sessionId, coverId) {
  399.     var photos = null, cover = undefined;
  400.     return app.getSessionFromDB(sessionId).then(function (session) {
  401.         photos = session.photos;
  402.  
  403.  
  404.         photos.forEach(function (item, index, photos) {
  405.             if (item !== null && item.id === coverId) {
  406.                 cover = item.base64;
  407.             }
  408.         });
  409.  
  410.         if (cover === undefined) return ('./images/placeholder/cancel.png');
  411.         return cover;
  412.     });
  413. }
  414.  
  415. app.updatePhotosInSession = function (id, photos) {
  416.     return db.sessions.update(id, { photos: photos });
  417. }
  418.  
  419. app.setSessionEmail = function (id, email) {
  420.     return db.sessions.update(id, { email: email });
  421. }
  422.  
  423. //render things
  424. app.renderActiveSessionsV2 = function () {
  425.     var self = this,
  426.         $list = $('#sessions_list'),
  427.         html = '', lCount = 0, fCount = 0;
  428.  
  429.     $list.empty();
  430.     $list.append('<svg class="progress-circular"><circle class="progress-circular__primary" cx="50%" cy="50%" r="20%" fill="none" stroke-width="10%" stroke-miterlimit="10"></svg>');
  431.  
  432.     var c = db.sessions.count(function (ca) {
  433.         fCount = ca;
  434.         if (fCount == 0) {
  435.             $('.progress-circular').remove();
  436.             $list.append('You are not have a active session');
  437.         }
  438.     });
  439.  
  440.     db.sessions.each(function (session) {
  441.         if (session.user === self.store.logged.currentUser) {
  442.             self.getCoverV2(session.id, session.cover).then(function (cover) {
  443.                 lCount++;
  444.                 var src = $('#active-session-template').text(),
  445.                     template = Handlebars.compile(src),
  446.                     html = template({
  447.                         'id': session.id,
  448.                         'cover': cover,
  449.                         'date': session.date,
  450.                         'title': session.title.replace(/ - /g, ', ')
  451.                     });
  452.  
  453.                 if ((lCount == (fCount - (fCount - lCount)))) {
  454.                     $('.progress-circular').remove();
  455.                     $list.append(html);
  456.                 }
  457.             });
  458.         }
  459.     });
  460. }
  461.  
  462. app.renderPhotosV2 = function () {
  463.     var $this = this;
  464.  
  465.     return $this.getSessionFromDB($this.currentSessionId).then(function (session) {
  466.         var photos = session.photos;
  467.  
  468.         var $list = $('#photos_list');
  469.         $list.empty();
  470.  
  471.         if (photos.length > 0) {
  472.             photos.forEach(function (item, index, photos) {
  473.                 if (item !== null) {
  474.                     var src = $('#photo-template').text();
  475.                     var template = Handlebars.compile(src);
  476.                     var html = template({ 'id': item.id, 'photo-link': item.base64 });
  477.                     $list.append(html);
  478.                 }
  479.             });
  480.         } else {
  481.             $list.append('<p>You are should take a more photo!</p>');
  482.         }
  483.     });
  484. }
  485.  
  486. // APP END
  487. ons.ready(function () {
  488.     var nav = document.getElementById('nav');
  489.  
  490.     if (localStorage.getItem('watcutData') !== null) {
  491.         console.log('-> Loading data');
  492.         app.loadData();
  493.     }
  494.  
  495.     // nav.pushPage('./templates/signin.html');
  496.     if (app.store.logged.remember === false) {
  497.         app.logout();
  498.         nav.resetToPage('./templates/signin.html', {
  499.             animation: "slide"
  500.         });
  501.     }
  502.  
  503.     if (app.store.logged.token === undefined || app.store.logged.token === null)
  504.         nav.resetToPage('./templates/signin.html', {
  505.             animation: "slide"
  506.         });
  507.     else {
  508.         if (app.store.showSplash == null)
  509.             nav.resetToPage('./templates/splash.html', {
  510.                 animation: "slide"
  511.             });
  512.         else
  513.             nav.resetToPage('./templates/session.html', {
  514.                 animation: "slide"
  515.             });
  516.     }
  517.  
  518.     document.addEventListener('show', function (event) {
  519.         initActivity(event.target.id);
  520.     });
  521.  
  522.     function initActivity(activityId) {
  523.         console.log('Activated activity: ' + activityId);
  524.         switch (activityId) {
  525.             case 'signin': signInActivity(); break;
  526.             case 'splash': splashActivity(); break;
  527.             case 'session': sessionActivity(); break;
  528.             case 'tags-session': tagsActivity(); break;
  529.             case 'camera': cameraActivity(); break;
  530.             case 'photos': photosActivity(); break;
  531.         }
  532.     }
  533.  
  534.     function splashActivity() {
  535.         console.log('[SPLASH ACTIVITY]');
  536.         if (isChrome) {
  537.             alert('app.store.cameraEnable: ' + app.store.cameraEnable);
  538.             if (app.store.cameraEnable === null) {
  539.                 if (!isNative) {
  540.                     checkCamera().then(function (res) {
  541.                         console.log('-> Camera is ' + (res ? 'enabled' : 'disabled'));
  542.                         app.store.cameraEnable = res;
  543.                         Init();
  544.                     }).catch(function (err) {
  545.                         console.log('-> Error: ' + err);
  546.                         console.log('-> Camera is disabled');
  547.                         app.store.cameraEnable = false;
  548.                         Init();
  549.                     });
  550.                 } else {
  551.                     app.store.cameraEnable = false;
  552.                     console.log('-> Camera is disabled');
  553.                     Init();
  554.                 }
  555.             } else {
  556.                 console.log('-> Camera is ' + (app.store.cameraEnable ? 'enabled' : 'disabled'));
  557.                 Init();
  558.             }
  559.         } else {
  560.             console.log('-> Camera is disabled');
  561.             app.store.cameraEnable = false;
  562.             Init();
  563.         }
  564.  
  565.         function Init() {
  566.             app.store.showSplash = false;
  567.             nav.resetToPage('./templates/session.html', {
  568.                 animation: "slide"
  569.             });
  570.         }
  571.     }
  572.  
  573.     function signInActivity() {
  574.         app.setRemember($(this).is(':checked'));
  575.         if ((app.store.logged.token !== null && app.store.logged.token !== ''))
  576.             if (app.store.showSplash == null)
  577.                 nav.resetToPage('./templates/splash.html', {
  578.                     animation: "slide"
  579.                 });
  580.             else
  581.                 nav.pushPage('./templates/session.html');
  582.  
  583.         $('.sigin__checkbox').on('change', function () {
  584.             app.setRemember($(this).is(':checked'));
  585.         });
  586.  
  587.         document.querySelector('ons-button[name="signin-btn"]').onclick = function () {
  588.             var login = document.querySelector('input[name="signin-login"]').value,
  589.                 password = document.querySelector('input[name="signin-password"]').value;
  590.  
  591.  
  592.             if (login != '' && password != '') {
  593.                 $('ons-button[name="signin-btn"]').text('');
  594.                 $('ons-button[name="signin-btn"]').append('<svg class="progress-circular"><circle class="progress-circular__primary" cx="50%" cy="50%" r="20%" fill="none" stroke-width="10%" stroke-miterlimit="10"></svg>');
  595.  
  596.                 var data = "username=" + encodeURIComponent(login) + "&password=" + encodeURIComponent(password);
  597.                 var xhr = new XMLHttpRequest();
  598.                 xhr.withCredentials = true;
  599.  
  600.                 xhr.addEventListener("readystatechange", function () {
  601.                     if (this.readyState === 4) {
  602.                         console.log(this.readyState);
  603.                         if (this.status === 200) {
  604.                             var d = JSON.parse(this.responseText);
  605.  
  606.                             app.setCurrentUser(login);
  607.                             app.setToken(d.token);
  608.  
  609.                             if (app.store.showSplash == null)
  610.                                 nav.resetToPage('./templates/splash.html', {
  611.                                     animation: "slide"
  612.                                 });
  613.                             else nav.pushPage('./templates/session.html');
  614.  
  615.                         } else {
  616.                             ons.notification.alert({ title: 'Error', message: 'Invalid login or passrword! Try again!' });
  617.                             $('.progress-circular').remove();
  618.                             $('ons-button[name="signin-btn"]').text('Log In');
  619.                         }
  620.                     }
  621.                 });
  622.  
  623.                 xhr.open("POST", "https://butybook.cz/wp-json/jwt-auth/v1/token");
  624.                 xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
  625.                 xhr.send(data);
  626.  
  627.             } else {
  628.                 ons.notification.alert({ title: 'Error', message: 'Login or password is empty!' });
  629.             }
  630.         };
  631.     }
  632.  
  633.     function sessionActivity() {
  634.         app.currentSessionId = null;
  635.         app.renderActiveSessionsV2();
  636.  
  637.         $('body').on('click', '.active-sessions__delete', function () {
  638.             var $id = $(this).data('session-id');
  639.  
  640.             app.removeSessionByIdV2($id).then(function () {
  641.                 $('ons-list-item[data-session-id="' + $id + '"]').remove();
  642.                 app.renderActiveSessionsV2();
  643.                 app.currentSessionId = null;
  644.             });
  645.         });
  646.  
  647.         $('body').on('click', '.active-sessions__item', function () {
  648.             var id = $(this).data('session-id');
  649.  
  650.             app.getSessionFromDB(id).then(function (session) {
  651.                 app.currentSessionId = session.id;
  652.                 nav.pushPage('./templates/tags-new-session.html', { data: { session: session } });
  653.             });
  654.         });
  655.  
  656.         document.querySelector('ons-button[name="new-session-btn"]').addEventListener('click', function () {
  657.             nav.pushPage('./templates/tags-new-session.html');
  658.         });
  659.  
  660.         document.querySelector('ons-button[name="sign-out"]').addEventListener('click', function () {
  661.             app.logout();
  662.             nav.resetToPage('./templates/signin.html');
  663.         });
  664.     }
  665.  
  666.     function tagsActivity() {
  667.         var sessionData,
  668.             photos = [],
  669.             isLoaded = false,
  670.             startId = 0;
  671.  
  672.  
  673.  
  674.         if (app.currentSessionId !== null && app.currentSessionId !== undefined) {
  675.             app.getSessionFromDB(app.currentSessionId).then(function (session) {
  676.                 sessionData = session;
  677.                 photos = sessionData.photos;
  678.                 isLoaded = true;
  679.  
  680.                 if (photos.length > 0)
  681.                     startId = photos.length;
  682.                 else startId = 0;
  683.  
  684.                 loadSession();
  685.  
  686.  
  687.                 $('.session-footer__new').hide();
  688.                 $('.session-footer__continue').show();
  689.                 document.querySelector('ons-button[name="continue"]').onclick = function () {
  690.                     app.currentSessionId = sessionData.id;
  691.                     nav.pushPage('./templates/photos.html', {
  692.                         animation: "slide"
  693.                     });
  694.                 };
  695.             });
  696.         } else {
  697.             saveCutSetting();
  698.             if (app.store.cameraEnable) $('.camera-enabled').show();
  699.             else $('.camera-disabled').show();
  700.         }
  701.  
  702.         $('input[type="radio"]').on('change', function () {
  703.             saveCutSetting();
  704.         });
  705.  
  706.         $('input[name="special"]').on('change', function () {
  707.             saveCutSetting();
  708.         });
  709.  
  710.         function loadSession() {
  711.             $('input[value="' + sessionData.gender + '"]').prop('checked', true);
  712.             $('input[value="' + sessionData.specials + '"]').prop('checked', true);
  713.  
  714.             $('input[value="' + sessionData.type + '"]').prop('checked', true);
  715.             $('input[value="' + sessionData.color + '"]').prop('checked', true);
  716.             $('input[value="' + sessionData.cut + '"]').prop('checked', true);
  717.  
  718.             $('input[value="' + sessionData.coloration + '"]').prop('checked', true);
  719.         }
  720.  
  721.         function saveCutSetting() {
  722.             var gender = $('input[name="gender"]:checked').val(),
  723.                 hairType = $('input[name="hair-type"]:checked').val(),
  724.                 hairColour = $('input[name="hair-color"]:checked').val(),
  725.                 hairLength = $('input[name="hair-length"]:checked').val(),
  726.                 specials = $('input[name="special"]:checked').val(),
  727.                 coloration = $('input[name="hair-coloration"]:checked').val(),
  728.                 newSession = null;
  729.  
  730.             if (isLoaded) {
  731.                 newSession = {
  732.                     'id': sessionData.id, 'user': sessionData.user, 'gender': gender, 'type': hairType,
  733.                     'color': hairColour, 'cut': hairLength, 'specials': specials, 'coloration': coloration,
  734.                     'email': sessionData.email, 'cover': sessionData.cover, 'date': sessionData.date,
  735.                     'photos': sessionData.photos
  736.                 };
  737.             } else {
  738.                 newSession = {
  739.                     'id': app.generateId(), 'user': app.store.logged.currentUser, 'gender': gender, 'type': hairType,
  740.                     'color': hairColour, 'cut': hairLength, 'specials': specials, 'coloration': coloration,
  741.                     'email': app.defaultEmail, 'cover': 0, 'date': getCurrentDate(),
  742.                     'photos': []
  743.                 };
  744.             }
  745.  
  746.             var title = convertTitle(newSession);
  747.             newSession.title = title;
  748.  
  749.             sessionData = newSession;
  750.             isLoaded = true;
  751.  
  752.             app.saveToDB(sessionData);
  753.         }
  754.  
  755.  
  756.         if (window.File && window.FileReader && window.FileList && window.Blob) {
  757.             $('body').on('change', '#addPhoto2', function () {
  758.                 var modal = document.getElementById('loader');
  759.                 modal.show();
  760.  
  761.                 $this = $(this);
  762.                 var files = $(this).prop('files');
  763.  
  764.                 alert('Files count (if >1 => input got a file) : ' + files.length);
  765.  
  766.                 for (var i = 0; i < files.length; i++) {
  767.                     alert('#1');
  768.                     var file = files[i];
  769.                     var reader = new FileReader();
  770.                     alert('#2');
  771.                     reader.onloadend = function () {
  772.                     alert('#3');
  773.  
  774.                         var tempImg = new Image();
  775.                         tempImg.src = reader.result;
  776.                         tempImg.onload = function () {
  777.                     alert('#4');
  778.  
  779.                             var MAX_WIDTH = 900;
  780.                             var MAX_HEIGHT = 600;
  781.                             var tempW = tempImg.width;
  782.                             var tempH = tempImg.height;
  783.                             if (tempW > tempH) {
  784.                                 if (tempW > MAX_WIDTH) {
  785.                                     tempH *= MAX_WIDTH / tempW;
  786.                                     tempW = MAX_WIDTH;
  787.                                 }
  788.                             } else {
  789.                                 if (tempH > MAX_HEIGHT) {
  790.                                     tempW *= MAX_HEIGHT / tempH;
  791.                                     tempH = MAX_HEIGHT;
  792.                                 }
  793.                             }
  794.                     alert('#5');
  795.  
  796.                             function drawRotated(degrees, img, canvas, ctx, o) {
  797.                                 var w = tempW,
  798.                                     h = tempH;
  799.                                 ctx.clearRect(0, 0, canvas.width, canvas.height);
  800.                                 ctx.save();
  801.  
  802.                                 if (o == 8) {
  803.                                     ctx.translate(0, canvas.height * 1.5);
  804.                                     w *= 1.5;
  805.                                     h *= 1.5;
  806.                                 }
  807.                                 else if (o == 6) {
  808.                                     ctx.translate(canvas.width / 2 + tempW / 2, -canvas.height + tempH / 6);
  809.                                     w *= 1.5;
  810.                                     h *= 1.5;
  811.                                 }
  812.                                 else if (o == 3) {
  813.                                     ctx.translate(canvas.width, canvas.height);
  814.                                 }
  815.  
  816.                                 ctx.rotate(degrees * Math.PI / 180);
  817.  
  818.                                 ctx.drawImage(img, 0, 0, w, h); //draw the image ;)
  819.                                 ctx.restore();
  820.                             }
  821.  
  822.                     alert('#6');
  823.                             var canvas = document.createElement('canvas');
  824.                             canvas.width = tempW;
  825.                             canvas.height = tempH;
  826.                     alert('#7');
  827.  
  828.                             var ctx = canvas.getContext("2d");
  829.                             ctx.drawImage(this, 0, 0, tempW, tempH);
  830.                     alert('#8');
  831.  
  832.                             var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(reader.result));
  833.                     alert('#9');
  834.                             switch (exif.Orientation) {
  835.                                 case 8:
  836.                                     drawRotated(-90, this, canvas, ctx, exif.Orientation);
  837.                                     break;
  838.                                 case 3:
  839.                                     drawRotated(180, this, canvas, ctx, exif.Orientation);
  840.                                     break;
  841.                                 case 6:
  842.                                     drawRotated(90, this, canvas, ctx, exif.Orientation);
  843.                                     break;
  844.                             }
  845.  
  846.                     alert('#10');
  847.  
  848.                             // setTimeout(function () {
  849.                             var base64 = canvas.toDataURL("image/jpeg");
  850.                     alert('#11');
  851.                             item = {
  852.                                 'id': startId++,
  853.                                 'base64': base64,
  854.                                 'selected': false,
  855.                                 'angle': 0
  856.                             };
  857.                     alert('#12');
  858.  
  859.                             photos.push(item);
  860.                     alert('#13');
  861.  
  862.                             if (i == files.length) {
  863.                     alert('#14');
  864.                                 setTimeout(function () {
  865.                                     app.updatePhotosInSession(sessionData.id, photos).then(function (updated) {
  866.                     alert('#15');
  867.                                         if (updated) {
  868.                                            
  869.                     alert('#16');
  870.                                             console.log('photos is updated');
  871.                                             app.currentSessionId = sessionData.id;
  872.                     alert('#17');
  873.                                             modal.hide();
  874.                                             nav.pushPage('./templates/photos.html');
  875.                                         } else console.log('not updated');
  876.                                     });
  877.                                 }, 1000);
  878.                             }
  879.                         }
  880.                     }
  881.  
  882.                     alert('#18');
  883.                     reader.readAsDataURL(file);
  884.                     alert('#19');
  885.                 }
  886.             });
  887.         } else {
  888.             alert('The File APIs are not fully supported in this browser.');
  889.         }
  890.  
  891.         if (isAndroid) {
  892.             document.querySelector('ons-button[name="take-photos-btn"]').onclick = function () {
  893.                 app.currentSessionId = sessionData.id;
  894.                 nav.pushPage('./templates/camera.html');
  895.             };
  896.         }
  897.  
  898.  
  899.         document.querySelector('ons-button[name="finish-later"]').onclick = function () {
  900.             app.currentSessionId = null;
  901.             nav.resetToPage('./templates/session.html', {
  902.                 animation: "slide"
  903.             });
  904.         };
  905.     }
  906.  
  907.     function cameraActivity() {
  908.         var sessionData = null,
  909.             cId = null,
  910.             photos = null;
  911.  
  912.         if (app.currentSessionId !== null && app.currentSessionId !== undefined) {
  913.             app.getSessionFromDB(app.currentSessionId).then(function (session) {
  914.                 sessionData = session;
  915.                 photos = sessionData.photos;
  916.  
  917.                 if (photos.length > 0)
  918.                     startId = photos.length;
  919.                 else startId = 0;
  920.             });
  921.         }
  922.  
  923.         var preview = document.getElementById('video'),
  924.             canvas = document.getElementById('canvas'),
  925.             width = preview.offsetWidth,
  926.             height = preview.offsetHeight,
  927.             cameraRun = false,
  928.             $flash = $('#flash');
  929.  
  930.         $('#canvas').attr('width', width);
  931.         $('#canvas').attr('height', height);
  932.  
  933.         var context = canvas.getContext('2d');
  934.  
  935.         document.getElementById('snap').addEventListener('click', function () {
  936.             if (cameraRun) {
  937.                 $flash.addClass('anim-flash');
  938.                 setTimeout(function () {
  939.                     $flash.removeClass('anim-flash');
  940.                 }, 400);
  941.  
  942.                 context.drawImage(preview, 0, 0, width, height);
  943.  
  944.                 var dataURL = canvas.toDataURL('image/jpeg', 0.5);
  945.                 document.getElementById('cnvimg').src = dataURL;
  946.  
  947.                 photos.push({ 'id': startId++, 'base64': dataURL, 'selected': false, 'angle': 0 });
  948.  
  949.  
  950.                 app.updatePhotosInSession(sessionData.id, photos).then(function (updated) {
  951.                     if (updated) { console.log('photo is captured'); }
  952.                     else { console.log('photo is not captured'); }
  953.                 });
  954.             }
  955.         });
  956.  
  957.         var devicesStore = [];
  958.         function gotDevices(deviceInfos) {
  959.             for (var i = 0; i !== deviceInfos.length; ++i) {
  960.                 var deviceInfo = deviceInfos[i];
  961.                 var deviceObj = {};
  962.  
  963.                 if (deviceInfo.kind === 'videoinput') {
  964.                     $('.camera-select').append('<option value=' + deviceInfo.deviceId + '>' + deviceInfo.label + '</option>');
  965.                 }
  966.  
  967.                 deviceObj = { id: deviceInfo.deviceId, label: deviceInfo.label };
  968.                 devicesStore.push(deviceObj);
  969.             }
  970.         }
  971.  
  972.         navigator.mediaDevices.enumerateDevices().then(gotDevices).catch(handleError);
  973.  
  974.         function gotStream(stream) {
  975.             window.stream = stream; // make stream available to console
  976.             preview.srcObject = stream;
  977.             return navigator.mediaDevices.enumerateDevices();
  978.         }
  979.  
  980.         function start() {
  981.             if (window.stream) {
  982.                 window.stream.getTracks().forEach(function (track) {
  983.                     track.stop();
  984.                 });
  985.             }
  986.  
  987.             var videoSource = $('.camera-select').val();
  988.             var constraints = {
  989.                 audio: false,
  990.                 // video: true,
  991.                 video: { deviceId: videoSource ? { exact: videoSource } : undefined }
  992.             };
  993.  
  994.             navigator.mediaDevices.getUserMedia(constraints).
  995.                 then(gotStream).catch(handleError);
  996.         }
  997.  
  998.         function handleError(error) {
  999.             console.log('navigator.getUserMedia error: ', error);
  1000.         }
  1001.  
  1002.         $('.camera-select').on('change', function () {
  1003.             console.log('Camera changed');
  1004.             start();
  1005.         })
  1006.  
  1007.         start();
  1008.         cameraRun = true;
  1009.  
  1010.         $('ons-button[name="continue"]').on('click', function () {
  1011.             nav.pushPage('./templates/photos.html', {
  1012.                 data: { session: sessionData }
  1013.             });
  1014.         });
  1015.  
  1016.  
  1017.         if (window.File && window.FileReader && window.FileList && window.Blob) {
  1018.             document.getElementById('add-photo').onchange = function () {
  1019.                 var files = document.getElementById('add-photo').files;
  1020.                 for (var i = 0; i < files.length; i++) {
  1021.                     var file = files[i];
  1022.                     var reader = new FileReader();
  1023.                     reader.onloadend = function () {
  1024.  
  1025.                         var tempImg = new Image();
  1026.                         tempImg.src = reader.result;
  1027.                         tempImg.onload = function () {
  1028.  
  1029.                             var MAX_WIDTH = 900;
  1030.                             var MAX_HEIGHT = 600;
  1031.                             var tempW = tempImg.width;
  1032.                             var tempH = tempImg.height;
  1033.                             if (tempW > tempH) {
  1034.                                 if (tempW > MAX_WIDTH) {
  1035.                                     tempH *= MAX_WIDTH / tempW;
  1036.                                     tempW = MAX_WIDTH;
  1037.                                 }
  1038.                             } else {
  1039.                                 if (tempH > MAX_HEIGHT) {
  1040.                                     tempW *= MAX_HEIGHT / tempH;
  1041.                                     tempH = MAX_HEIGHT;
  1042.                                 }
  1043.                             }
  1044.  
  1045.                             function drawRotated(degrees, img, canvas, ctx, o) {
  1046.                                 var w = tempW,
  1047.                                     h = tempH;
  1048.                                 ctx.clearRect(0, 0, canvas.width, canvas.height);
  1049.                                 ctx.save();
  1050.  
  1051.                                 if (o == 8) {
  1052.                                     ctx.translate(0, canvas.height * 1.5);
  1053.                                     w *= 1.5;
  1054.                                     h *= 1.5;
  1055.                                 }
  1056.                                 else if (o == 6) {
  1057.                                     ctx.translate(canvas.width / 2 + tempW / 2, -canvas.height + tempH / 6);
  1058.                                     w *= 1.5;
  1059.                                     h *= 1.5;
  1060.                                 }
  1061.                                 else if (o == 3) {
  1062.                                     ctx.translate(canvas.width, canvas.height);
  1063.                                 }
  1064.  
  1065.                                 ctx.rotate(degrees * Math.PI / 180);
  1066.  
  1067.                                 ctx.drawImage(img, 0, 0, w, h); //draw the image ;)
  1068.                                 ctx.restore();
  1069.                             }
  1070.  
  1071.                             var canvas = document.createElement('canvas');
  1072.                             canvas.width = tempW;
  1073.                             canvas.height = tempH;
  1074.  
  1075.                             var ctx = canvas.getContext("2d");
  1076.                             ctx.drawImage(this, 0, 0, tempW, tempH);
  1077.  
  1078.                             var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(reader.result));
  1079.                             switch (exif.Orientation) {
  1080.                                 case 8:
  1081.                                     drawRotated(-90, this, canvas, ctx, exif.Orientation);
  1082.                                     break;
  1083.                                 case 3:
  1084.                                     drawRotated(180, this, canvas, ctx, exif.Orientation);
  1085.                                     break;
  1086.                                 case 6:
  1087.                                     drawRotated(90, this, canvas, ctx, exif.Orientation);
  1088.                                     break;
  1089.                             }
  1090.  
  1091.                             var base64 = canvas.toDataURL("image/jpeg"),
  1092.                                 item = {
  1093.                                     'id': startId++,
  1094.                                     'base64': base64,
  1095.                                     'selected': false,
  1096.                                     'angle': 0
  1097.                                 };
  1098.  
  1099.                             photos.push(item);
  1100.  
  1101.                             if (i == files.length) {
  1102.                                 setTimeout(function () {
  1103.                                     app.updatePhotosInSession(sessionData.id, photos).then(function (updated) {
  1104.                                         if (updated) {
  1105.                                             console.log('updated!');
  1106.                                             nav.pushPage('./templates/photos.html');
  1107.                                         } else console.log('not updated');
  1108.                                     });
  1109.                                 }, 1000);
  1110.                             }
  1111.                         }
  1112.                     }
  1113.                     reader.readAsDataURL(file);
  1114.                 }
  1115.             };
  1116.         } else {
  1117.             alert('The File APIs are not fully supported in this browser.');
  1118.         }
  1119.     }
  1120.  
  1121.     function photosActivity() {
  1122.         //checked parametr
  1123.         var sessionData = null,
  1124.             cId = null,
  1125.             photos = null,
  1126.             startId = 0;
  1127.  
  1128.         if (!app.store.cameraEnable) {
  1129.             $('ons-if.cam-button').remove();
  1130.         }
  1131.  
  1132.         app.getSessionFromDB(app.currentSessionId).then(function (session) {
  1133.             sessionData = session;
  1134.             photos = sessionData.photos;
  1135.             cId = sessionData.cover;
  1136.  
  1137.             if (photos.length > 0)
  1138.                 startId = photos.length;
  1139.             else startId = 0;
  1140.  
  1141.             if (sessionData.email !== null && sessionData.email !== app.defaultEmail) $('#email-client').val(sessionData.email);
  1142.  
  1143.             app.renderPhotosV2().then(function () {
  1144.                 setCover($('.list-item[data-photo-id="' + cId + '"]'));
  1145.  
  1146.                 photos.forEach(function (item, index, photos) {
  1147.                     if (item.selected) {
  1148.                         setPhotoSelected($('.list-item[data-photo-id="' + item.id + '"]'))
  1149.                     }
  1150.                 });
  1151.  
  1152.                 calculateSelected();
  1153.             });
  1154.         });
  1155.  
  1156.         //list-item
  1157.         $('body').unbind().on('click', '.overlay-event', function () {
  1158.             setPhotoSelected($(this).parent().parent(), false);
  1159.         });
  1160.  
  1161.         //[START]
  1162.         function calculateSelected() {
  1163.             var count = 0;
  1164.  
  1165.             app.getSessionFromDB(app.currentSessionId).then(function (session) {
  1166.                 var photos = session.photos;
  1167.  
  1168.                 if (photos.length > 0) {
  1169.                     photos.forEach(function (item, index, photos) {
  1170.                         if (item.selected) count++;
  1171.                     });
  1172.                 }
  1173.  
  1174.  
  1175.                 if (count >= 1) $('ons-button[name="publish"]').prop('disabled', false);
  1176.                 else $('ons-button[name="publish"]').prop('disabled', true);
  1177.             });
  1178.         }
  1179.  
  1180.         function setPhotoSelected(el, setOnly) {
  1181.             var photoId = el.data('photo-id'),
  1182.                 isSelected = el.data('isselected'),
  1183.                 isCover = el.data('iscover');
  1184.  
  1185.             if (isCover !== 1) {
  1186.                 if (isSelected === 0) {
  1187.                     el.data('isselected', 1);
  1188.                     el.find('.overlay-selected').addClass('active');
  1189.                     app.togglePhotoSelectedV2(photoId, true).then(function () {
  1190.                         calculateSelected();
  1191.                     });
  1192.  
  1193.                     calculateSelected();
  1194.                 } else if (isSelected === 1 && setOnly === false) {
  1195.                     el.data('isselected', 0);
  1196.                     el.find('.overlay-selected').removeClass('active');
  1197.                     app.togglePhotoSelectedV2(photoId, false).then(function () {
  1198.                         calculateSelected();
  1199.                     });
  1200.                 }
  1201.             }
  1202.         }
  1203.  
  1204.         function setCover(el) {
  1205.             var isCover = el.data('iscover'),
  1206.                 photoId = el.data('photo-id');
  1207.  
  1208.             if (isCover === 0) {
  1209.                 setPhotoSelected(el, true);
  1210.  
  1211.                 $('.overlay-cover').removeClass('active');
  1212.                 $('.list-item').data('iscover', 0);
  1213.  
  1214.                 el.data('iscover', 1);
  1215.                 el.find('.overlay-cover').addClass('active');
  1216.  
  1217.                 db.sessions.update(app.currentSessionId, { cover: photoId }).then(function (isUpd) {
  1218.                     if (isUpd) console.log('Cover is updated');
  1219.                     else console.log('Cover is not updated');
  1220.                 });
  1221.             }
  1222.         }
  1223.  
  1224.  
  1225.         var timeOut = 0;
  1226.         $('body').on('mousedown touchstart', '.overlay-event', function (e) { //list-item
  1227.             console.log('click');
  1228.             var $this = $(this).parent().parent();
  1229.             console.log($this);
  1230.             timeOut = setTimeout(function () {
  1231.                 setCover($this);
  1232.                 console.log('hold!');
  1233.             }, 1000);
  1234.         }).bind('mouseup mouseleave touchend', function () {
  1235.             clearInterval(timeOut);
  1236.         });
  1237.  
  1238.  
  1239.         if (window.File && window.FileReader && window.FileList && window.Blob) {
  1240.             document.getElementById('addPhoto').onchange = function () {
  1241.                 app.getSessionFromDB(app.currentSessionId).then(function (session) {
  1242.                     var photos = session.photos;
  1243.                     var files = document.getElementById('addPhoto').files;
  1244.                     for (var i = 0; i < files.length; i++) {
  1245.                         var file = files[i];
  1246.                         var reader = new FileReader();
  1247.                         reader.onloadend = function () {
  1248.                             var tempImg = new Image();
  1249.                             tempImg.src = reader.result;
  1250.  
  1251.                             tempImg.onload = function () {
  1252.                                 var MAX_WIDTH = 900;
  1253.                                 var MAX_HEIGHT = 600;
  1254.                                 var tempW = tempImg.width;
  1255.                                 var tempH = tempImg.height;
  1256.                                 if (tempW > tempH) {
  1257.                                     if (tempW > MAX_WIDTH) {
  1258.                                         tempH *= MAX_WIDTH / tempW;
  1259.                                         tempW = MAX_WIDTH;
  1260.                                     }
  1261.                                 } else {
  1262.                                     if (tempH > MAX_HEIGHT) {
  1263.                                         tempW *= MAX_HEIGHT / tempH;
  1264.                                         tempH = MAX_HEIGHT;
  1265.                                     }
  1266.                                 }
  1267.  
  1268.                                 function drawRotated(degrees, img, canvas, ctx, o) {
  1269.                                     var w = tempW,
  1270.                                         h = tempH;
  1271.                                     ctx.clearRect(0, 0, canvas.width, canvas.height);
  1272.                                     ctx.save();
  1273.  
  1274.                                     if (o == 8) {
  1275.                                         ctx.translate(0, canvas.height * 1.5);
  1276.                                         w *= 1.5;
  1277.                                         h *= 1.5;
  1278.                                     }
  1279.                                     else if (o == 6) {
  1280.                                         ctx.translate(canvas.width / 2 + tempW / 2, -canvas.height + tempH / 6);
  1281.                                         w *= 1.5;
  1282.                                         h *= 1.5;
  1283.                                     }
  1284.                                     else if (o == 3) {
  1285.                                         ctx.translate(canvas.width, canvas.height);
  1286.                                     }
  1287.  
  1288.                                     ctx.rotate(degrees * Math.PI / 180);
  1289.  
  1290.                                     ctx.drawImage(img, 0, 0, w, h); //draw the image ;)
  1291.                                     ctx.restore();
  1292.                                 }
  1293.  
  1294.                                 var canvas = document.createElement('canvas');
  1295.                                 canvas.width = tempW;
  1296.                                 canvas.height = tempH;
  1297.  
  1298.                                 var ctx = canvas.getContext("2d");
  1299.                                 ctx.drawImage(this, 0, 0, tempW, tempH);
  1300.  
  1301.                                 var exif = EXIF.readFromBinaryFile(base64ToArrayBuffer(reader.result));
  1302.                                 switch (exif.Orientation) {
  1303.                                     case 8:
  1304.                                         drawRotated(-90, this, canvas, ctx, exif.Orientation);
  1305.                                         break;
  1306.                                     case 3:
  1307.                                         drawRotated(180, this, canvas, ctx, exif.Orientation);
  1308.                                         break;
  1309.                                     case 6:
  1310.                                         drawRotated(90, this, canvas, ctx, exif.Orientation);
  1311.                                         break;
  1312.                                 }
  1313.  
  1314.                                 var base64 = canvas.toDataURL("image/jpeg"),
  1315.                                     item = {
  1316.                                         'id': startId++,
  1317.                                         'base64': base64,
  1318.                                         'selected': false,
  1319.                                         'angle': 0
  1320.                                     };
  1321.  
  1322.                                 photos.push(item);
  1323.  
  1324.                                 if (i == files.length) {
  1325.                                     app.updatePhotosInSession(sessionData.id, photos).then(function (updated) {
  1326.                                         if (updated) {
  1327.                                             app.renderPhotosV2().then(function () {
  1328.                                                 app.getSessionFromDB(sessionData.id).then(function (session) {
  1329.                                                     photos = session.photos;
  1330.                                                     setCover($('.list-item[data-photo-id="' + cId + '"]'));
  1331.  
  1332.                                                     photos.forEach(function (item, index, photos) {
  1333.                                                         if (item.selected) setPhotoSelected($('.list-item[data-photo-id="' + item.id + '"]'))
  1334.                                                     });
  1335.  
  1336.                                                     calculateSelected();
  1337.                                                 });
  1338.  
  1339.                                                 console.log('updated');
  1340.                                             });
  1341.  
  1342.                                         } else console.log('not updated');
  1343.                                     });
  1344.                                 }
  1345.                             }
  1346.                         }
  1347.  
  1348.                         reader.readAsDataURL(file);
  1349.                     }
  1350.                 });
  1351.             };
  1352.         } else {
  1353.             alert('The File APIs are not fully supported in this browser.');
  1354.         }
  1355.  
  1356.         $('#email-client').on('click', function () {
  1357.             $(this).removeAttr('value');
  1358.         });
  1359.  
  1360.         $('#email-client').on('change', function () {
  1361.             var $email = $(this).val();
  1362.             app.setSessionEmail(app.currentSessionId, $email).then(function () {
  1363.                 console.log('Email changed');
  1364.             });
  1365.         });
  1366.  
  1367.  
  1368.         $('ons-button[name="back-btn"]').on('click', function () {
  1369.             $('#photos_list').empty();
  1370.             nav.resetToPage('./templates/tags-new-session.html', {
  1371.                 animation: "slide"
  1372.             });
  1373.         });
  1374.  
  1375.         $('ons-button[name="finish-later"]').on('click', function () {
  1376.             $('#photos_list').empty();
  1377.             app.currentSessionId = null;
  1378.             nav.resetToPage('./templates/session.html', {
  1379.                 animation: "slide"
  1380.             });
  1381.         });
  1382.  
  1383.         if (isAndroid) {
  1384.             $('ons-button[name="take-photos-btn"]').on('click', function () {
  1385.                 $('#photos_list').empty();
  1386.                 nav.resetToPage('./templates/camera.html', {
  1387.                     animation: "slide"
  1388.                 });
  1389.             });
  1390.         }
  1391.  
  1392.         $('ons-button[name="publish"]').on('click', function () {
  1393.             if (navigator.onLine === false) {
  1394.                 ons.notification.confirm({
  1395.                     message: 'No internet connection. You can save a Cut and upload later.',
  1396.                     callback: function (t) {
  1397.                         if (t === 1) {
  1398.                             app.currentSessionId = null;
  1399.                             nav.resetToPage('./templates/session.html', {
  1400.                                 animation: "slide"
  1401.                             });
  1402.                         }
  1403.                     }
  1404.                 });
  1405.  
  1406.             } else {
  1407.                 var modal = document.getElementById('modal');
  1408.                 modal.show();
  1409.  
  1410.                 //post data on server
  1411.                 app.sendData(app.currentSessionId, function () {
  1412.                     app.removeSessionByIdV2(app.currentSessionId).then(function () {
  1413.                         app.currentSessionId = null;
  1414.                         modal.hide();
  1415.                         nav.resetToPage('./templates/session.html', {
  1416.                             animation: "slide"
  1417.                         });
  1418.                     });
  1419.  
  1420.                 }, function (err) {
  1421.                     ons.notification.confirm({
  1422.                         title: err + ' 403 ',
  1423.                         message: 'Save and upload later?',
  1424.                         callback: function (t) {
  1425.                             if (t === 1) {
  1426.                                 app.saveCurrentSession();
  1427.                                 nav.resetToPage('./templates/session.html', {
  1428.                                     animation: "slide"
  1429.                                 });
  1430.                             } else {
  1431.                                 modal.hide();
  1432.                             }
  1433.                         }
  1434.                     });
  1435.                 });
  1436.             }
  1437.         });
  1438.     }
  1439.  
  1440.     // Service Worker
  1441.     // if ('serviceWorker' in navigator) {
  1442.     //     navigator.serviceWorker
  1443.     //         .register('./service-worker.js')
  1444.     //         .then(function () { console.log('Service Worker Registered'); });
  1445.     // }
  1446. });
  1447.  
  1448.  
  1449. function convertTitle(session) {
  1450.     var newTitle = '';
  1451.  
  1452.     if (session.specials === '7') newTitle += 'kids - ';
  1453.  
  1454.     switch (parseInt(session.cut)) {
  1455.         case 4: newTitle += 'long - '; break;
  1456.         case 3: newTitle += 'medium - '; break;
  1457.         case 2: newTitle += 'short - '; break;
  1458.         case 22: newTitle += 'asymmetric - '; break;
  1459.     }
  1460.  
  1461.     switch (parseInt(session.color)) {
  1462.         case 13: newTitle += 'blond - '; break;
  1463.         case 14: newTitle += 'brown - '; break;
  1464.         case 17: newTitle += 'dark - '; break;
  1465.         case 15: newTitle += 'red - '; break;
  1466.         case 23: newTitle += 'other - '; break;
  1467.     }
  1468.  
  1469.     switch (parseInt(session.gender)) {
  1470.         case 5: newTitle += 'male - '; break;
  1471.         case 6: newTitle += 'female - '; break;
  1472.     }
  1473.  
  1474.     switch (parseInt(session.type)) {
  1475.         case 10: newTitle += 'curly - '; break;
  1476.         case 11: newTitle += 'straight - '; break;
  1477.         case 18: newTitle += 'wavy - '; break;
  1478.     }
  1479.  
  1480.     switch (parseInt(session.coloration)) {
  1481.         case 19: newTitle += 'colored'; break;
  1482.         case 20: newTitle += 'natural'; break;
  1483.         case 21: newTitle += 'melir'; break;
  1484.     }
  1485.  
  1486.     return newTitle;
  1487. }
  1488.  
  1489. function dataURLtoBlob(dataurl) {
  1490.     var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
  1491.         bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  1492.     while (n--) {
  1493.         u8arr[n] = bstr.charCodeAt(n);
  1494.     }
  1495.     return new Blob([u8arr], { type: mime });
  1496. }
  1497.  
  1498. function getBase64(file, callback) {
  1499.     var reader = new FileReader();
  1500.  
  1501.     reader.addEventListener('load', function () {
  1502.         callback(reader.result);
  1503.     }, false);
  1504.  
  1505.     reader.readAsDataURL(file);
  1506. }
  1507.  
  1508. function resizeImage(file, callback) {
  1509.     var canvas = document.getElementById('canvas-resize');
  1510.  
  1511.     var img = document.createElement("img");
  1512.     var reader = new FileReader();
  1513.     reader.onload = function (e) {
  1514.         img.src = e.target.result;
  1515.  
  1516.     }
  1517.     reader.readAsDataURL(file);
  1518.  
  1519.     var ctx = canvas.getContext("2d");
  1520.     ctx.drawImage(img, 0, 0);
  1521.  
  1522.     var MAX_WIDTH = 900,
  1523.         MAX_HEIGHT = 600,
  1524.         width = img.width,
  1525.         height = img.height;
  1526.  
  1527.     if (width > height) {
  1528.         if (width > MAX_WIDTH) {
  1529.             height *= MAX_WIDTH / width;
  1530.             width = MAX_WIDTH;
  1531.         }
  1532.     } else {
  1533.         if (height > MAX_HEIGHT) {
  1534.             width *= MAX_HEIGHT / height;
  1535.             height = MAX_HEIGHT;
  1536.         }
  1537.     }
  1538.  
  1539.     canvas.width = width;
  1540.     canvas.height = height;
  1541.     var ctx = canvas.getContext("2d");
  1542.     ctx.drawImage(img, 0, 0, width, height);
  1543.  
  1544.     var dataurl = canvas.toDataURL("image/png");
  1545.     callback(dataurl);
  1546. }
  1547.  
  1548. function getCurrentDate() {
  1549.     var today = new Date();
  1550.     var dd = today.getDate();
  1551.     var mm = today.getMonth() + 1; //January is 0!
  1552.  
  1553.     var yyyy = today.getFullYear();
  1554.  
  1555.     if (dd < 10) {
  1556.         dd = '0' + dd;
  1557.     }
  1558.     if (mm < 10) {
  1559.         mm = '0' + mm;
  1560.     }
  1561.  
  1562.     var today = dd + '.' + mm + '.' + yyyy;
  1563.     return today;
  1564. }
  1565.  
  1566. function base64ToArrayBuffer(base64) {
  1567.     base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
  1568.     var binaryString = atob(base64);
  1569.     var len = binaryString.length;
  1570.     var bytes = new Uint8Array(len);
  1571.     for (var i = 0; i < len; i++) {
  1572.         bytes[i] = binaryString.charCodeAt(i);
  1573.     }
  1574.     return bytes.buffer;
  1575. }
Add Comment
Please, Sign In to add comment