var App = { cartHighlightEnabled: false, currentPage: null, slogans: ['order food in 5 seconds'], service: '/api/', cached: {}, cart: {}, community: null, page: {}, config: null, order: { cardChanged: false, pay_type: 'card', delivery_type: 'delivery', tip: '10' }, _init: false, _pageInit: false, deletedDishes : [], selectedCategory : false }; function _deleteCategoryDialog(){ $('body').on('click', '.jqui-button.button-delete', function(){ var category_id = $(this).parent('.ui-accordion-content').prev('h3').data().id_category; var categories = App.restaurantObject.categories(); var catOptions = ''; for(var i = 0; i < categories.length; i++) { var disabled = false if (categories[i].id_category == category_id) { disabled = ' disabled="disabled" '; } catOptions += ''; } var html = '
' + '

You are about to delete this category. Existing dishes in the category will be moved to another category.

' + '
' + '

Are you sure you want to delete the category?

' + '
'; $(html).dialog({ resizable: false, height: 200, width: 400, modal: true, buttons: { Delete: function() { var to_id = $('select', this).val(); deleteCategory(category_id, to_id); $(this).dialog('close'); $(this).remove(); }, Cancel: function() { $(this).dialog('close'); $(this).remove(); } } }); }); } /** * Populates notifications types with empty fields to be inserted * * @return void */ function _loadEmptyNotifications() { var types = ['sms', 'email', 'phone', 'url', 'fax']; for(var i in types) { var notification = { id_notification: '', type: types[i], value: '', active: false, } _loadNotification(notification); } } /** * Sets the notifications in the restaurant form * * @param notifications */ function _loadNotification(notification) { var $wrapper = 'div.check-content.' + notification.type; // console.log($wrapper); $wrapper = $($wrapper); var active = parseInt(notification.active) ? 'checked="checked"' : ''; var id = parseInt(notification.id) ? notification.id : ''; html = '
' + '' + ''+ '
'; $wrapper.append(html); } /** * Load the restaurant * * @return void */ function _loadRestaurant() { var restaurant = this; var checkswap = { 'delivery_fee_check' : 'delivery_fee', 'delivery_min_check': 'delivery_min', 'fee_restaurant_check': 'fee_restaurant', 'fee_customer_check': 'fee_customer', 'id_community_check': 'id_community' }; $('.admin-restaurant-form input, .admin-restaurant-form select, .admin-restaurant-form textarea').each(function() { if ($(this).attr('type') == 'checkbox') { if (restaurant[$(this).attr('name')] == 1 && $(this).attr('value') == '1') { $(this).click(); } if (restaurant[$(this).attr('name')] == 0 && $(this).attr('value') == '0') { $(this).click(); } } else { $(this).val(restaurant[$(this).attr('name')]); } for (var x in checkswap) { if ($(this).attr('name') == x) { if (restaurant[checkswap[x]] && restaurant[checkswap[x]] != '0') { //$('input[name="' + x + '"][value="0"]').prop('checked', false); //$('input[name="' + x + '"][value="1"]').prop('checked', true); $('input[name="' + x + '"][value="1"]').click(); } else { //$('input[name="' + x + '"][value="0"]').prop('checked', true); //$('input[name="' + x + '"][value="1"]').prop('checked', false); $('input[name="' + x + '"][value="0"]').click(); } } } }); App.restaurant = restaurant.id_restaurant; // Should be App.id_restaurant IMHO App.restaurantObject = restaurant; // and this one should rellay be App.restaurant $('.admin-restaurant-content').html(''); var notifications = restaurant.notifications(); for (var i in notifications) { _loadNotification(notifications[i]); } _loadEmptyNotifications(); _newNotificationFields(); var categories = restaurant.categories(); var isDishes = false; var $categoriesContainer = $('
'); $('.admin-restaurant-dishes .admin-restaurant-content').append($categoriesContainer); /** * Swip all categories * * @todo Use the App.createCategory * @todo Encapsulate the categories loading in a private _loadCategories() method */ for (var i in categories) { var dishes = categories[i].dishes(); var name = categories[i].name; var sort = (categories[i].sort && (categories[i].sort != 'null')) ? categories[i].sort : 0; var $categoryTab = $('

'+ name+'

' + '
' + '
'+ '
' + '' + '' + '
' + '
'); $categoriesContainer.append($categoryTab); for (var x in dishes) { App.showDish(dishes[x]); isDishes = true; } } $('.accordion').accordion({ collapsible: true, active: false, heightStyle: "content", activate: function( event, ui ){ var speed = 100; var accordionOptions = $('.accordion').accordion('option'); setTimeout(function() { $('.accordion').accordion('destroy'); $('.accordion').accordion(accordionOptions); }, 1.1 * speed); } }); _deleteCategoryDialog(); // end of loadingCategories; if (!isDishes) { $('input[name="dish_check"][value="0"]').prop('checked', true); $('input[name="dish_check"][value="1"]').prop('checked', false); $('.admin-restaurant-dishes').hide(); } else { $('input[name="dish_check"][value="0"]').prop('checked', false); $('input[name="dish_check"][value="1"]').prop('checked', true); $('.admin-restaurant-dishes').show(); } var days = { 'sun': 'Sunday', 'mon': 'Monday', 'tue': 'Tuesday', 'wed': 'Wednesday', 'thu': 'Thursday', 'fri': 'Friday', 'sat': 'Saturday' }; for (var d in days) { var day = $('
' + days[d] + '
'); var dayWrap = $('
').appendTo(day); dayWrap.after('
'); if (!restaurant._hours) { $('input[name="hours_check"][value="0"]').prop('checked', true); $('input[name="hours_check"][value="1"]').prop('checked', false); $('.admin-restaurant-hours').hide(); } else { $('input[name="hours_check"][value="0"]').prop('checked', false); $('input[name="hours_check"][value="1"]').prop('checked', true); $('.admin-restaurant-hours').show(); var dayitem = restaurant._hours[d]; for (var x in dayitem) { var row = $('
'); row.append('' + ' TO ' + ' '); dayWrap.append(row); } } var row = $('
'); row.append(' TO '); dayWrap.append(row); $('.admin-restaurant-hours').append(day); } } /** * Adds a new hours range if they are all filled up * * @return void */ function _newNotificationFields() { var inputSelector = '.notification-wrap input[name="notification-value"]'; $(document).on('keyup', inputSelector, function() { var $container = $(this).closest('.check-content'); var allfull = true; $container.find(inputSelector).each(function() { if ($(this).val() == '') { allfull = false; } }); if (allfull) { var notification = { id_notification: '', value: '', active: false, } var types = ['sms', 'email', 'phone', 'url', 'fax']; for (var i in types) { if ($container.hasClass(types[i])) { notification.type = types[i]; } } _loadNotification(notification); } }); } /** * Method to be called to save the Dish Categories * * @param function complete What to trigger after the categories are stored * * @return void * * @todo returned elements need to be reloaded */ function _saveCategories(complete) { var selector = 'input , select, textarea'; var container = '#categories .labeled-fields.category'; var elements = []; $(container).each(function(){ var inputs = $(selector, this); var data = $(this).parent().prev().data(); data = getValues(inputs, data); elements[elements.length] = data; }); $.post('/api/restaurant/' + App.restaurant + '/categories', {elements: elements}, function() { if (complete) { complete(); } }); } /** * Method to be called to save all dishes * * @param function compelte What to trigger after the dishes are stored * * @return void */ function saveDishes (complete) { var selector = 'input.dataset-dish, select.dataset-dish, textarea.dataset-dish'; var dishes = []; $('.admin-food-item-wrap').each(function() { var id = $(this).attr('data-id_dish'); var values = getValues($(this).find(selector), {}); var dish = { name: values['dish-name'], description: values['dish-description'], price: values['dish-price'], id_category: values['dish-id_category'], active: values['dish-active'], sort: values['dish-sort'] }; if (id) { dish.id_dish = id; } dish.optionGroups = []; $(this).find('.admin-dish-options .admin-dish-options-wrapper').each(function() { var id = $(this).attr('data-parent'); var name = $(this).find('.admin-dish-options-title').html(); name = name.substr(0,name.length-1); var optionGroup = { name: name, 'default': values['dish-options-default'], type: $(this).attr('data-type'), price: $(this).attr('data-modifies_price') == 'true' ? true : false, options: [] }; if (id) { optionGroup.id_option = id; } $(this).find('.dish-options').each(function() { var id = $(this).attr('data-id_option'); var values = getValues($(this).find('input'), {}); if (values['dish-options-name']) { var option = { name: values['dish-options-name'], price: values['dish-options-price'] || 0.00, 'default': $(this).find('input[type="checkbox"], input[type="radio"]').prop('checked'), sort: values['dish-options-sort'] }; if (id) { option.id_option = id; } optionGroup.options[optionGroup.options.length] = option; } }); dish.optionGroups[dish.optionGroups.length] = optionGroup; }); // Just to make sure that the name was typed and the user don't clicked at 'Add another dish?' by mistake. if( dish.name && dish.name != 'null' && dish.name != '' ){ $.post('/api/restaurant/' + App.restaurant + '/save-dish', {dish: dish}, function() {}); } }); if( App.deletedDishes.length > 0 ){ $.each( App.deletedDishes, function( i, value ) { $.post('/api/restaurant/' + App.restaurant + '/delete-dish', {id_dish: value}, function() { if (complete && i == App.deletedDishes.length - 1 ) { complete(); } }); }); } else { complete(); } } /** * Method to be called to save notifications * * @param function compelte What to trigger after the dishes are stored * * @return void * * @todo wasn't able to take the function out becaues of the getValue() method which needs to be refactorized and moved out * @todo returned elements need to be reloaded */ function _saveNotifications(complete) { var selector = 'input.dataset-notification, select.dataset-notification, textarea.dataset-notification'; var elements = []; $('.notification-wrap').each(function() { var id = $(this).attr('data-id_notification'); var values = getValues($(this).find(selector), {}); var element = { active: values['notification-active'], value: values['notification-value'] }; var types = ['sms', 'email', 'phone', 'url', 'fax']; for (var i in types) { var $container = $(this).closest('.check-content'); if ($container.hasClass(types[i])) { element.type = types[i]; } } if (id) { element.id_notification = id; } elements[elements.length] = element; }); $.post('/api/restaurant/' + App.restaurant + '/notifications', {elements: elements}, function() { if (complete) { complete(); } }); } /** * * @param all */ function saveRestaurant (all) { var html = '
' + '
' + '

Please wait while saving...

' + '' + '
' + '
'; $(html).dialog({ resizable: false, height: 160, width: 315, modal: true, closeOnEscape: false, open: function(event, ui) { $(".ui-dialog-titlebar-close, .ui-icon-closethick", ui.dialog || ui).hide(); } }); $(".ui-dialog-titlebar-close, .ui-icon-closethick").hide(); var selector = 'input.dataset-restaurant, select.dataset-restaurant, textarea.dataset-restaurant'; var id = App.restaurant; if (id) { App.cache('Restaurant', id, function() { var restaurant = getValues(selector, this); restaurant.save(function() { if (all) { saveHours(function() { _saveCategories(function() { saveDishes(function() { _saveNotifications(function() { location.href = '/admin/restaurants/' + App.restaurant; }); }); }); }); } }); }); } else { var restaurant = getValues(selector, {}); restaurant = new Restaurant(restaurant); restaurant.save(function(r) { App.cache('Restaurant', r.id_restaurant, function() { App.restaurant = this.id_restaurant; if (all) { saveHours(function() { _saveCategories(function(){ saveDishes(function() { _saveNotifications(function() { location.href = '/admin/restaurants/' + App.restaurant; }); }); }); }); } else { locatifion.href = '/admin/restaurants/' + App.restaurant; } }); }); } }; function saveHours (complete) { var selector = '.hours-date-hour input'; var id = App.restaurant; if (id) { App.cache('Restaurant', id, function() { var h = getValues(selector, {}); var hours = {'sun': [],'mon': [],'tue': [],'wed': [],'thu': [],'fri': [],'sat': []}; var vals = getValues('input.dataset-restaurant', {}); if (vals.hours_check) { for (var d in hours) { for (var x in h[d + '-open']) { if (!h[d + '-open'][x]) continue; hours[d][hours[d].length] = [App.unFormatTime(h[d + '-open'][x]), App.unFormatTime(h[d + '-close'][x])]; } } } // console.log(hours); $.post('/api/restaurant/' + id + '/hours', {hours: hours}, function() { if (complete) { complete(); } }); }); } }; function deleteCategory(from_id, to_id) { var $toDelete = $('h3[data-id_category="'+from_id+'"]'); var dishes = $('.admin-food-item-wrap', $toDelete.next()); // $('select[name="dish-id_category"]').val(to_id); $('h3[data-id_category="'+to_id+'"]').next().append(dishes); $('select[name="dish-id_category"]').each(function(){ if( $(this).val() == from_id ){ $(this).val( to_id ); } }); $toDelete.next().remove(); $toDelete.remove(); } function getValues(selector, restaurant) { $(selector).each(function() { var name, value, group = false; if ($(this).attr('name').match(/^.*\[\]$/)) { group = true; name = $(this).attr('name').replace(/^(.*)\[\]$/,'$1'); if (!restaurant[name]) { restaurant[name] = []; } } else { name = $(this).attr('name'); } if ($(this).attr('type') == 'checkbox' || $(this).attr('type') == 'radio') { value = $(this).prop('checked') ? true : false; } else { value = $(this).val(); } if (group) { restaurant[name][restaurant[name].length] = value; } else { restaurant[name] = value; } }); return restaurant; } App.loadRestaurant = function(id_restaurant) { App.cache('Restaurant', id_restaurant , _loadRestaurant); }; /** * Generates HTML to show dish and it's items * * @todo Not sure if hide purges HTML or what. */ App.showDish = function(dishItem) { dishItem = $.extend({ id_dish: '', // id_category: '', name: '', description: '', price: '' }, dishItem); var dish = $(''); dish.append('
' + '' + dishItem.name + '' + '($' + dishItem.price + ')
') var content = $('
'); var padding = $('
'); dish.append(content); content.append(padding); var options = $('
'); var basicOptions = $('
'); var basicWrapper = $('
Basic options:
') .append(basicOptions); var optGroups = []; if (dishItem.options) { var opts = dishItem.options(); options.append(basicWrapper); var options_with_children = {}; for (var x in opts) { var option = opts[x]; if (option.id_option_parent) { options_with_children[option.id_option_parent] = true; } } for (var x in opts) { var option = opts[x]; if (option.id_option_parent) { continue; } if (option.type == 'check') { if( !options_with_children[ option.id ] ){ basicOptions.append(App.returnOption(option,option.type)); } else { var optionAdder = $('
'); var optionWrapper = $('
' + option.name + ':
') .append(optionAdder); var select = $(''); for (var i in opts) { if (opts[i].id_option_parent == option.id_option) { optionAdder.append(App.returnOption(opts[i],option.type,option.id_option)); } } optionAdder.append(App.returnOption({price: '',name:'',id_option:''},option.type,option.id_option)); options.append(optionWrapper); } } basicOptions.append(App.returnOption({price: '',name:'',id_option:''},'check')); options.append('
' + '' + '
'); } var dishDescription = dishItem.description ? dishItem.description : ''; var categories = App.restaurantObject.categories(); var categoryOptions = ''; if (!dishItem.id_category) { console.log('ERROR, no category for this dish'); } for (var i in categories) { var selected = (categories[i].id_category == dishItem.id_category) ? ' selected="selected" ' : ''; categoryOptions += ''; } var active = (parseInt(dishItem.active)) ? 'checked="checked"' : ''; dishItem.sort = ( dishItem.sort ) ? dishItem.sort : ( $('[data-id_category="'+ dishItem.id_category +'"] + div').find('.admin-food-item').length ? ( $('[data-id_category="'+ dishItem.id_category +'"] + div').find('.admin-food-item').length + 1 ) : 1 ); padding .append('') .append('
') .append('
') .append('