var Alloy = require("alloy");
var UTIL = require("utilities");
var settingsManager = require("settingsManager");
var serverClient = require("serverClient");
var userManager = require("userManager");
var catalogManager = require("catalogManager");
Ti.API.info("1");
var resourceManager = require("resourceManager");
Ti.API.info("2");
var shopPointsManager = require("shopPointsManager");
Alloy.Globals.resourceDownloader = new(require("ResourceDownloader"));
var APP = {
Catalog: null,
Settings: null,
/**
* All the component nodes (e.g. tabs)
* @type {Object}
*/
Nodes: [],
Network: {
type: Ti.Network.networkTypeName,
online: Ti.Network.online
},
Device: {
isHandheld: Alloy.isHandheld,
isTablet: Alloy.isTablet,
type: Alloy.isHandheld ? "handheld" : "tablet",
os: null,
name: null,
version: Ti.Platform.version,
versionMajor: parseInt(Ti.Platform.version.split(".")[0], 10),
versionMinor: parseInt(Ti.Platform.version.split(".")[1], 10),
width: Ti.Platform.displayCaps.platformWidth > Ti.Platform.displayCaps.platformHeight ? Ti.Platform.displayCaps.platformHeight : Ti.Platform.displayCaps.platformWidth,
height: Ti.Platform.displayCaps.platformWidth > Ti.Platform.displayCaps.platformHeight ? Ti.Platform.displayCaps.platformWidth : Ti.Platform.displayCaps.platformHeight,
dpi: Ti.Platform.displayCaps.dpi,
orientation: Ti.Gesture.orientation == Ti.UI.LANDSCAPE_LEFT || Ti.Gesture.orientation == Ti.UI.LANDSCAPE_RIGHT ? "LANDSCAPE" : "PORTRAIT",
statusBarOrientation: null
},
/**
* Whether or not to cancel the loading screen open because it's already open
* @type {Boolean}
*/
cancelLoading: false,
/**
* The previous screen in the hierarchy
* @type {Object}
*/
previousScreen: null,
/**
* The view stack for controllers
* @type {Array}
*/
controllerStacks: [],
/**
* The view stack for modals
* @type {Array}
*/
modalStack: [],
/**
* Current controller view stack index
* @type {Number}
*/
currentStack: -1,
/**
* The main app window
* @type {Object}
*/
MainWindow: null,
/**
* The view stack for master views
* @type {Array}
*/
Master: [],
/**
* The view stack for detail views
* @type {Array}
*/
Detail: [],
/**
* The global view all screen controllers get added to
* @type {Object}
*/
GlobalWrapper: null,
/**
* The global view all content screen controllers get added to
* @type {Object}
*/
ContentWrapper: null,
/**
* Slide Menu widget
* @type {Object}
*/
SlideMenu: null,
/**
* Whether or not the slide menu is open
* @type {Boolean}
*/
SlideMenuOpen: false,
/**
* Whether or not the slide menu is engaged
*
* **NOTE: Turning this false temporarily disables the slide menu**
* @type {Boolean}
*/
SlideMenuEngaged: true,
settingsManager: settingsManager,
userManager: userManager,
shopPointsManager: shopPointsManager,
checkExistAssetsFile: function(){
var assetsFile = Ti.Filesystem.getFile(Ti.Filesystem.getApplicationDataDirectory() + '/datatmp' , 'assets.json');
var interval = setInterval(function(){
if(!assetsFile.exists()){
Ti.API.info("FILE DOES NOT EXIST!!!");
} else {
clearInterval(interval);
var asd = resourceManager.runAssetMananger();
// Ti.API.info("resmanger, data is", asd);
resourceManager.queue(asd.assets);
Ti.API.info("START runAssetMananger");
}
}, 5000);
},
init: function() {
if(OS_ANDROID) {
APP.MainWindow.addEventListener("androidback", APP.backButtonObserver);
}
APP.initDB();
var oldDay;
var currentDay = new Date();
newDay = currentDay.getDate() +'/'+ currentDay.getMonth() + '/' + currentDay.getFullYear();
if (oldDay != newDay) {
oldDay = newDay;
if( /* check hashes*/1) {
//Alloy.Globals.DownloadQueue.CatalogImageDownloader = require('CatalogImageDownloader');
Alloy.Globals.resourceDownloader.start();
}
}
// Первое посещение раздела Список покупок
// Alloy.Globals.isFirstVisitShoppingList = true;
// Ti.App.Properties.setBool('isFirstVisit', true);
// Список покупок
Alloy.Globals.ShoppingList = [];
// Determine device characteristics
APP.determineDevice();
// Reads in the JSON config file
APP.loadContent();
APP.downloadNewRes();
APP.checkExistAssetsFile();
APP.build();
// Open the main window
APP.MainWindow.open();
// The initial screen to show
if (APP.Settings.debugLayout) {
APP.handleNavigation(0);
} else {
if (APP.userManager.isLogin()) {
APP.handleNavigation(0);
} else {
APP.handleNavigation(8);
}
}
},
/*
*
* */
initDB: function() {
Alloy.Globals.utensil_item = Alloy.Collections.utensil_item = Alloy.createCollection("utensil_item");
Alloy.Globals.utensil_item.add(Alloy.Globals.gifts);
},
downloadNewRes: function() {
var jsons = ["", "assets" , "settings", "pos"];
var datatmpDir = Ti.Filesystem.getFile(Ti.Filesystem.getApplicationDataDirectory(), 'datatmp');
if(!datatmpDir.exists()){
datatmpDir.createDirectory();
}
_.each(jsons, function(json){
Alloy.Globals.resourceDownloader.add({
url : Alloy.Globals.Settings.server.url + "/" + json,
path : Titanium.Filesystem.applicationDataDirectory + 'datatmp/' + json + '.json'
});
Ti.API.info("downloadNewRes", Alloy.Globals.Settings.server.url + "/" + json);
Ti.API.info("downloadNewRes", Titanium.Filesystem.applicationDataDirectory + 'datatmp/' + json + '.json');
});
},
/**
* Determines the device characteristics
*/
determineDevice: function() {
if(OS_IOS) {
APP.Device.os = "IOS";
if(Ti.Platform.osname.toUpperCase() == "IPHONE") {
APP.Device.name = "IPHONE";
} else if(Ti.Platform.osname.toUpperCase() == "IPAD") {
APP.Device.name = "IPAD";
}
} else if(OS_ANDROID) {
APP.Device.os = "ANDROID";
APP.Device.name = Ti.Platform.model.toUpperCase();
// Fix the display values
APP.Device.width = (APP.Device.width / (APP.Device.dpi / 160));
APP.Device.height = (APP.Device.height / (APP.Device.dpi / 160));
}
},
/**
* Loads in the appropriate controller and config data
*/
loadContent: function() {
var contentFile = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, "app.json");
if(!contentFile.exists()) {
contentFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory + "data/app.json");
}
var content = contentFile.read();
var data;
try {
data = JSON.parse(content.text);
} catch(_error) {
APP.log("error", "Unable to parse downloaded JSON, reverting to packaged JSON");
contentFile = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory + "data/app.json");
if(contentFile.exists()) {
content = contentFile.read();
data = JSON.parse(content.text);
} else {
APP.log("error", "Unable to parse local JSON, dying");
alert("Unable to open the application");
return;
}
}
APP.Settings = data.settings;
if (APP.Settings.debugLayout) {
APP.Nodes = data.tabs;
} else {
APP.Nodes = data.tabsProduction;
}
// load settings
Alloy.Globals.Settings = data.settings; // after this point you can use server api and so on
// TEST try to load settings from server
// TODO: reload app if settings is updated
serverClient.get_settings(
function(s) {
Ti.API.info("Settings loaded");
},
function(s) {
Ti.API.error("Error loading settings from server, using local copy");
}
);
// TEST try to load settings from server
// TODO: reload app if settings is updated
// serverClient.login_user(
// "av", 1, "00000001",
// function(s) {
// Ti.API.info("login user - ok");
// Ti.API.info(s);
// },
// function(s) {
// Ti.API.error("Error login user");
// }
// );
// Ti.API.info("settings loaded");
// load current catalog
catalogManager.sweepOutdatedLocalCatalog();
var prebundledCatalog = catalogManager.loadPrebundledCatalog();
var cachedCatalog = catalogManager.loadCachedCatalog();
APP.Catalog = cachedCatalog || prebundledCatalog;
Ti.API.info("* Catalog loaded, revision: " + APP.Catalog.getRevision());
// TEST load assets
// real url by asset: one
/*
var au1 = resourceManager.parseAssetUrl("asset:190x120.KV-G.jpg");
Ti.API.info("au1", au1);
var ai1 = resourceManager.getAssetInfo("190x120.KV-G.jpg");
Ti.API.info("ai1", ai1);
var as1 = resourceManager.getAssetStatus(ai1);
Ti.API.info("as1", as1);
var cactionHtml = resourceManager.normalizeAssetLinksInText("<b>Собирай марки и получай бокалы</b>" +
"<p><img src=\"asset:190x120.KV-G.jpg\"/></p>");
Ti.API.info("cactionHtml", cactionHtml);
*/
resourceManager.checkAssetsUptodate();
APP.shopPointsManager.loadJson();
Ti.API.info("POS LOAD START");
Ti.App.Properties.setObject("shopPoints",APP.shopPointsManager.getData());
// Ti.API.info("core: getData is", Ti.App.Properties.getObject("shopPoints", []));
///////////////
// load nodes
for(var i = 0, x = APP.Nodes.length; i < x; i++) {
APP.Nodes[i].index = i;
}
if(typeof APP.Settings.useSlideMenu == "undefined") {
APP.Settings.useSlideMenu = true;
}
},
getRecipesListForDraw: function(_recipesList) {
var newRecipesList = [];
for (var i = 0; i < _recipesList.length; i++) {
var now = new Date().getTime();
if (_recipesList[i].hasOwnProperty('startDate') && _recipesList[i].hasOwnProperty('endDate')) {
var startDate = APP.getTimeStamp(_recipesList[i].startDate);
var endDate = APP.getTimeStamp(_recipesList[i].endDate);
if (now >= startDate && now <= endDate) {
newRecipesList.push(_recipesList[i]);
}
} else if (_recipesList[i].hasOwnProperty('startDate')) {
var startDate2 = APP.getTimeStamp(_recipesList[i].startDate);
if (now >= startDate2) {
newRecipesList.push(_recipesList[i]);
}
} else if (_recipesList[i].hasOwnProperty('endDate')) {
var endDate2 = APP.getTimeStamp(_recipesList[i].endDate);
if (now <= endDate2) {
newRecipesList.push(_recipesList[i]);
}
} else {
newRecipesList.push(_recipesList[i]);
}
}
return newRecipesList;
},
/*
* format date from "yyyy-mm-dd" to timestamp
* @param {String} _dateString The date in format "yyyy-mm-dd"
* */
getTimeStamp: function(_dateString) {
// new Date("yyyy-mm-dd").getTime() не работает, поэтому используем эту функцию
var year = Number(_dateString.split('-')[0]);
var month = Number(_dateString.split('-')[1]);
var day = Number(_dateString.split('-')[2]);
var date = new Date();
date.setFullYear(year);
date.setMonth(month - 1, day);
return date.getTime();
},
/*
* format date from "yyyy-mm-dd" to format "dd.mm.yyyy"
* @param {String} _dateString The date in format "yyyy-mm-dd"
* */
getActionDateString: function(_dateString) {
var year = _dateString.split('-')[0];
var month = _dateString.split('-')[1];
var day = _dateString.split('-')[2];
return day + '.' + month + '.' + year;
},
/*
* format date from "yyyy-mm-dd" to format "dd monthName yyyy"
* @param {String} _dateString The date in format "yyyy-mm-dd"
* @param {Boolean} _withoutYear if true - add to string the yaer
* */
getNewDateFormat: function(_dateString, _withoutYear) {
var newDateString;
var year = _dateString.split('-')[0];
var month = _dateString.split('-')[1];
var day = _dateString.split('-')[2];
// убрать передний 0 из числа
// 06 -> 6
if (day.slice(0, 1) == '0') {
day = day.slice(1);
}
var newMonthString = '';
switch (month) {
case '01': {
newMonthString = 'января';
break;
}
case '02': {
newMonthString = 'февраля';
break;
}
case '03': {
newMonthString = 'марта';
break;
}
case '04': {
newMonthString = 'апреля';
break;
}
case '05': {
newMonthString = 'мая';
break;
}
case '06': {
newMonthString = 'июня';
break;
}
case '07': {
newMonthString = 'июля';
break;
}
case '08': {
newMonthString = 'августа';
break;
}
case '09': {
newMonthString = 'сентября';
break;
}
case '10': {
newMonthString = 'октября';
break;
}
case '11': {
newMonthString = 'ноября';
break;
}
case '12': {
newMonthString = 'декабря';
break;
}
}
if (_withoutYear) {
newDateString = day + ' ' + newMonthString;
} else {
newDateString = day + ' ' + newMonthString + ' ' + year + ' г.';
}
return newDateString;
},
build: function() {
var nodes = [];
var imageFolder = "/icons/";
// проверить, подходит ли текущая дата под сроки акции (actions.current)
// больше старта и меньше окончания
// сравнивать лучше в ms из getTime()
var isAction = false;
if (Alloy.Globals.actions.current && Alloy.Globals.actions.current.startDate && Alloy.Globals.actions.current.endDate) {
var startDateTimeStamp = APP.getTimeStamp(Alloy.Globals.actions.current.startDate.toString());
var endDateTimeStamp = APP.getTimeStamp(Alloy.Globals.actions.current.endDate.toString());
var currentDate = new Date().getTime();
if (currentDate >= startDateTimeStamp && currentDate <= endDateTimeStamp) isAction = true;
}
for (var i = 0, x = APP.Nodes.length; i < x; i++) {
// рисуем либо Доп.марки либо Спецпредложения в зависимости от того, проходит сейчас акция или нет
// акция идет - рисуем Доп.марки
// акция не идет - рисуем Спецпредложения
if (!APP.Settings.debugLayout && APP.Nodes[i].page && APP.Nodes[i].page == 'extra_stamp_offers') {
if (isAction) {
// Акция идет - рисуем Доп.марки
APP.Nodes[i].page = 'extra_stamp_offers';
APP.Nodes[i].title = 'Дополнительные марки';
} else {
// Акция не идет - рисуем Спецпредложения
APP.Nodes[i].page = 'special_offers';
APP.Nodes[i].title = 'Специальные предложения';
}
}
if (!APP.Settings.debugLayout && i == x - 1) {
continue;
}
// массив с элементами для отрисовки бокового меню
nodes.push({
id: i,
title: APP.Nodes[i].title,
image: UTIL.fileExists(imageFolder + APP.Nodes[i].image + ".png") ? imageFolder + APP.Nodes[i].image + ".png" : null,
controller: APP.Nodes[i].type.toLowerCase(),
countEnabled: APP.Nodes[i].countEnabled ? APP.Nodes[i].countEnabled : null,
page: APP.Nodes[i].page ? APP.Nodes[i].page : null
});
}
APP.buildMenu(nodes);
},
buildMenu: function(_nodes) {
APP.log("debug", "APP.buildMenu");
APP.SlideMenu.init({
nodes: _nodes,
color: {
headingBackground: APP.Settings.colors.primary,
headingText: APP.Settings.colors.theme == "dark" ? "#FFF" : "#000"
}
});
// Move everything down to take up the TabGroup space
APP.ContentWrapper.bottom = "0dp";
// Add a handler for the nodes (make sure we remove existing ones first)
APP.SlideMenu.Nodes.removeEventListener("click", APP.handleMenuClick);
APP.SlideMenu.Nodes.addEventListener("click", APP.handleMenuClick);
// Listen for gestures on the main window to open/close the slide menu
APP.GlobalWrapper.addEventListener("swipe", function(_event) {
Ti.API.info("swipe core", JSON.stringify(_event.source));
if (_event.source.globalSwipe == false || _event.source.globalSwipe == 'false') {
Ti.API.info("swipe return");
return;
}
if(APP.SlideMenuEngaged) {
if(_event.direction == "right") {
APP.openMenu();
} else if(_event.direction == "left") {
APP.closeMenu();
}
}
});
},
/**
* Re-builds the app with newly downloaded JSON configration file
*/
rebuild: function() {
APP.log("debug", "APP.rebuild");
APP.SlideMenu.clear();
// Undo removal of TabGroup
APP.ContentWrapper.bottom = "60dp";
APP.currentStack = -1;
APP.previousScreen = null;
APP.controllerStacks = [];
APP.modalStack = [];
APP.hasDetail = false;
APP.currentDetailStack = -1;
APP.previousDetailScreen = null;
APP.detailStacks = [];
APP.Master = [];
APP.Detail = [];
APP.cancelLoading = false;
APP.loadingOpen = false;
// NOTICE
// The following section is abstracted for PEEK
APP.rebuildRestart();
},
/**
* Kicks off the newly re-built application
*/
rebuildRestart: function() {
Ti.API.debug("APP.rebuildRestart");
APP.loadContent();
APP.build();
if (APP.Settings.debugLayout) {
APP.handleNavigation(0);
} else {
APP.handleNavigation(8);
}
},
/**
* Handles the click event on a menu item
* @param {Object} _event The event
*/
handleMenuClick: function(_event) {
if(typeof _event.row.id !== "undefined" && typeof _event.row.id == "number") {
APP.closeSettings();
APP.handleNavigation(_event.row.id);
} else if(typeof _event.row.id !== "undefined" && _event.row.id == "settings") {
APP.openSettings();
}
APP.toggleMenu();
},
handleNavigation: function(_id) {
APP.log("debug", "APP.handleNavigation | " + APP.Nodes[_id].type);
// Requesting same screen as we're on
if(_id == APP.currentStack) {
// Do nothing
return;
} else {
APP.SlideMenu.setIndex(_id);
// Set current stack
APP.currentStack = _id;
// Create new controller stack if it doesn't exist
if(typeof APP.controllerStacks[_id] === "undefined") {
APP.controllerStacks[_id] = [];
}
// Set current controller stack
var controllerStack = APP.controllerStacks[_id];
// If we're opening for the first time, create new screen
// Otherwise, add the last screen in the stack (screen we navigated away from earlier on)
var screen;
APP.hasDetail = false;
APP.previousDetailScreen = null;
if (controllerStack.length > 0) {
// Retrieve the last screen
screen = controllerStack[controllerStack.length - 1];
} else {
// Create a new screen
var type = APP.Nodes[_id].type.toLowerCase();
var tabletSupport = APP.Nodes[_id].tabletSupport;
screen = Alloy.createController(type, APP.Nodes[_id]).getView();
// Add screen to the controller stack
controllerStack.push(screen);
}
// Add the screen to the window
APP.addScreen(screen);
// Reset the modal stack
APP.modalStack = [];
}
},
/**
* Open a child screen
* @param {String} _controller The name of the controller to open
* @param {Object} _params An optional dictionary of parameters to pass to the controller
* @param {Boolean} _modal Whether this is for the modal stack
* @param {Boolean} _sibling Whether this is a sibling view
*/
addChild: function(_controller, _params, _modal, _sibling) {
var stack;
// Determine if stack is associated with a tab
if(_modal) {
stack = APP.modalStack;
} else {
if(APP.Device.isHandheld || !APP.hasDetail) {
stack = APP.controllerStacks[APP.currentStack];
} else {
stack = APP.detailStacks[APP.currentDetailStack];
}
}
// Create the new screen controller
var screen = Alloy.createController(_controller, _params).getView();
if(_sibling) {
stack.pop();
}
// Add screen to the controller stack
stack.push(screen);
// Add the screen to the window
if(APP.Device.isHandheld || !APP.hasDetail || _modal) {
APP.addScreen(screen);
} else {
APP.addDetailScreen(screen);
}
},
/**
* Removes a child screen
* @param {Boolean} _modal Removes the child from the modal stack
*/
removeChild: function(_modal) {
var stack;
Ti.App.fireEvent("viewRemoveChild");
if(_modal) {
stack = APP.modalStack;
} else {
if(APP.Device.isTablet && APP.hasDetail) {
stack = APP.detailStacks[APP.currentDetailStack];
} else {
stack = APP.controllerStacks[APP.currentStack];
}
}
var screen = stack[stack.length - 1];
var previousStack;
var previousScreen;
var lastView = stack.pop();
lastView.fireEvent('destroy');
if(stack.length === 0) {
previousStack = APP.controllerStacks[APP.currentStack];
if(APP.Device.isHandheld || !APP.hasDetail) {
previousScreen = previousStack[previousStack.length - 1];
APP.addScreen(previousScreen);
} else {
previousScreen = previousStack[0];
if(_modal) {
APP.addScreen(previousScreen);
} else {
APP.addDetailScreen(previousScreen);
}
}
} else {
previousScreen = stack[stack.length - 1];
if(APP.Device.isHandheld || !APP.hasDetail) {
APP.addScreen(previousScreen);
} else {
if(_modal) {
APP.addScreen(previousScreen);
} else {
APP.addDetailScreen(previousScreen);
}
}
}
},
/**
* Removes all children screens
* @param {Boolean} _modal Removes all children from the stack
*/
removeAllChildren: function(_modal) {
var stack = _modal ? APP.modalStack : APP.controllerStacks[APP.currentStack];
for(var i = stack.length - 1; i > 0; i--) {
stack.pop();
}
APP.addScreen(stack[0]);
},
/**
* Global function to add a screen
* @param {Object} _screen The screen to add
*/
addScreen: function(_screen) {
if(_screen) {
APP.ContentWrapper.add(_screen);
if(APP.previousScreen) {
APP.removeScreen(APP.previousScreen);
}
APP.previousScreen = _screen;
}
},
/**
* Global function to remove a screen
* @param {Object} _screen The screen to remove
*/
removeScreen: function(_screen) {
if(_screen) {
APP.ContentWrapper.remove(_screen);
APP.previousScreen = null;
}
},
/**
* Adds a screen to the Master window
* @param {String} _controller The name of the controller to open
* @param {Object} _params An optional dictionary of parameters to pass to the controller
* @param {Object} _wrapper The parent wrapper screen to fire events to
*/
addMasterScreen: function(_controller, _params, _wrapper) {
var screen = Alloy.createController(_controller, _params).getView();
APP.Master[APP.currentStack].add(screen);
},
/**
* Shows the loading screen
*/
openLoading: function() {
APP.cancelLoading = false;
setTimeout(function() {
if(!APP.cancelLoading) {
APP.loadingOpen = true;
APP.GlobalWrapper.add(APP.Loading);
}
}, 100);
},
/**
* Closes the loading screen
*/
closeLoading: function() {
APP.cancelLoading = true;
if(APP.loadingOpen) {
APP.GlobalWrapper.remove(APP.Loading);
APP.loadingOpen = false;
}
},
/**
* Adds a screen to the Detail window
* @param {Object} _screen The screen to add
*/
addDetailScreen: function(_screen) {
if(_screen) {
APP.Detail[APP.currentStack].add(_screen);
if(APP.previousDetailScreen && APP.previousDetailScreen != _screen) {
var pop = true;
if(APP.detailStacks[APP.currentDetailStack][0].type == "PARENT" && _screen.type != "PARENT") {
pop = false;
}
APP.removeDetailScreen(APP.previousDetailScreen, pop);
}
APP.previousDetailScreen = _screen;
}
},
/**
* Removes a screen from the Detail window
* @param {Object} _screen The screen to remove
* @param {Boolean} _pop Whether to pop the item off the controller stack
*/
removeDetailScreen: function(_screen, _pop) {
if(_screen) {
APP.Detail[APP.currentStack].remove(_screen);
APP.previousDetailScreen = null;
if(_pop) {
var stack = APP.detailStacks[APP.currentDetailStack];
stack.splice(0, stack.length - 1);
}
}
},
/**
* Opens the Settings window
*/
openSettings: function() {
APP.log("debug", "APP.openSettings");
APP.addChild("settings", {}, true);
},
/**
* Closes all non-tab stacks
*/
closeSettings: function() {
if(APP.modalStack.length > 0) {
APP.removeChild(true);
}
},
/**
* Toggles the Slide Menu
*/
toggleMenu: function(_position) {
if(APP.SlideMenuOpen) {
APP.closeMenu();
} else {
APP.openMenu();
}
},
/**
* Opens the Slide Menu
*/
openMenu: function() {
APP.SlideMenu.Wrapper.left = "0dp";
APP.GlobalWrapper.animate({
left: APP.Device.width - 52 + 'dp',
duration: 250,
curve: Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
});
APP.SlideMenuOpen = true;
Ti.App.fireEvent('menuOpened');
},
/**
* Closes the Slide Menu
*/
closeMenu: function() {
APP.GlobalWrapper.animate({
left: "0dp",
duration: 250,
curve: Ti.UI.ANIMATION_CURVE_EASE_IN_OUT
});
APP.SlideMenuOpen = false;
Ti.App.fireEvent('menuClosed');
},
/*
* Get array of rubles and kopeks: ['rubles', 'kopeks']
* @param {Number} _number Price rubles.kopeks
* */
getRubKopek: function(_number) {
var newNumber = [];
var _string = _number.toString();
if (_string.search(/\./) != -1) {
// есть десятичная точка
newNumber.push(_string.split('.')[0]);
newNumber.push(_string.split('.')[1]);
} else {
// нет точки
newNumber.push(_string);
newNumber.push('00');
}
return newNumber;
},
log: function(_severity, _text) {
switch(_severity.toLowerCase()) {
case "debug":
Ti.API.debug(_text);
break;
case "error":
Ti.API.error(_text);
break;
case "info":
Ti.API.info(_text);
break;
case "log":
Ti.API.log(_text);
break;
case "trace":
Ti.API.trace(_text);
break;
case "warn":
Ti.API.warn(_text);
break;
}
},
drawRecipeInfo: function(_item, infoContainer) {
var titleFood = Ti.UI.createLabel({
text: _item.title,
width: Ti.UI.SIZE,
textAlign: 'left',
color: '#000',
font: {
fontFamily: 'GillSans-Light',
fontSize: '14dp'
},
height: '20dp',
left: '10dp',
top: '5dp'
});
infoContainer.add(titleFood);
var quantityInfoContainer = Ti.UI.createView({
width: Ti.UI.SIZE,
height: '14dp',
left: '10dp',
top: '27dp',
layout: 'horizontal'
});
var minutesContainer = Ti.UI.createView({
width: Ti.UI.SIZE,
height: '16dp',
left: '0dp',
top: '0dp',
layout: 'horizontal'
});
var minutesImage = Ti.UI.createImageView({
image: '/images/clocks.png',
width: '12dp',
height: '12dp',
left: '0dp',
top: '2dp'
});
minutesContainer.add(minutesImage);
var minutesLabel = Ti.UI.createLabel({
text: _item.duration,
width: Ti.UI.SIZE,
textAlign: 'left',
color: '#000',
font: {
fontFamily: 'GillSans',
fontSize: '14dp',
fontWeight: 'bold'
},
height: '16dp',
left: '5dp',
top: '-1dp'
});
minutesContainer.add(minutesLabel);
quantityInfoContainer.add(minutesContainer);
var personsContainer = Ti.UI.createView({
width: Ti.UI.SIZE,
height: '16dp',
left: '15dp',
top: '0dp',
layout: 'horizontal'
});
var personsImage = Ti.UI.createImageView({
image: '/images/person.png',
width: '12dp',
height: '12dp',
left: '0dp',
top: '2dp'
});
personsContainer.add(personsImage);
var personsLabel = Ti.UI.createLabel({
text: _item.persons,
width: Ti.UI.SIZE,
textAlign: 'left',
color: '#000',
font: {
fontFamily: 'GillSans',
fontSize: '14dp',
fontWeight: 'bold'
},
height: '16dp',
left: '5dp',
top: '-1dp'
});
personsContainer.add(personsLabel);
quantityInfoContainer.add(personsContainer);
infoContainer.add(quantityInfoContainer);
},
backButtonObserver: function(_event) {
APP.log("debug", "APP.backButtonObserver");
Ti.App.fireEvent('systemAndroidBack');
if(APP.modalStack.length > 0) {
APP.removeChild(true);
return;
} else {
var stack;
if(APP.Device.isHandheld || !APP.hasDetail) {
stack = APP.controllerStacks[APP.currentStack];
} else {
stack = APP.detailStacks[APP.currentDetailStack];
}
if(stack.length > 1) {
APP.removeChild();
} else {
APP.MainWindow.close();
}
}
}
};
module.exports = APP;