Skip to content

Instantly share code, notes, and snippets.

@fimak
Last active September 17, 2015 09:46
Show Gist options
  • Save fimak/17dd70253612ef7e98f1 to your computer and use it in GitHub Desktop.
Save fimak/17dd70253612ef7e98f1 to your computer and use it in GitHub Desktop.
Code Samples for SberbankTechnologies
Примеры кода:
https://gist.github.com/fimak/17dd70253612ef7e98f1
Bookyou-booking.js
Отрывок кода backbone моделей и вьюх из проекта бронирования услуг.
bookyou-dhtmlx-calendar.js
Отрывок кода, этого же проектаю Переопределял и дополнял некоторые функций библиотеки dhtmlx-calendar
Ссылка на проект - https://bookyou.ch/ - но он в каком то странном ссостоянии сейчас
flappybirdphaser-game.js
Изучал phaiser по туториалу, код игры.
learnpdd-game.js
код одной из игр по правилам дорожного движения
rafinad-somescript.js
отрывок кода из магазина платьев, ссылка на магазин в продакшене - http://rafinad-dress.ru/
почему то отсутсвует фильтр палтьев в продакшене у меня локально он еще остался.
Так же можете посмотреть js код социальной сети для знакомств которую я разрабатывал в 2012 году
https://github.com/fimak/jollyday/blob/master/themes/jolly/js/jolly.js
Примеры верстки:
http://rafinad-dress.ru/
https://foodbam.com
http://www.issart.com/en/
var bookingForm = function () {
var ServiceModel = Backbone.Model.extend();
var ServicesCollection = Backbone.Collection.extend({
model: ServiceModel,
url: BookyouAdmin.url.getServices
});
var ServiceCategoryModel = Backbone.Model.extend();
var ServiceCategoriesCollection = Backbone.Collection.extend({
model: ServiceCategoryModel
});
var EmployeeModel = Backbone.Model.extend();
var EmployeesCollection = Backbone.Collection.extend({
model: EmployeeModel
});
var EmployeeServiceModel = Backbone.Model.extend();
var EmployeesServicesCollection = Backbone.Collection.extend({
model: EmployeeServiceModel
});
var BookingView = Backbone.View.extend({
el: '#body-container',
services: new ServicesCollection(),
serviceCategories: new ServiceCategoriesCollection(),
employees: new EmployeesCollection(),
employeeServices: new EmployeesServicesCollection(),
successMessage: '',
errorMessage: '',
infoMessage: '',
unregisteredUser:'',
events: {
'change .booking-type': 'changeBookingType',
'change .datepicker': 'updateDatesAndTimes',
'click .predefined-from-time': 'changeFromTime',
'blur .tp': 'updateCustomDatesAndTimes',
'submit #create-reservation-form': 'submitForm'
},
changeBookingType: function (e) {
var currentType = $(e.currentTarget).val();
var serviceList = this.$el.find('#service-list');
var parentServiceList = serviceList.parent();
var typeAHead = this.$el.find('#client-type-a-head');
var email = this.$el.find('#email');
var phone = this.$el.find('#phone');
var appointmentDetails = this.$el.find('#appointment-details');
var notifications = this.$el.find('#notifications');
if (currentType.length > 0) {
if (currentType == 'event') {
serviceList.select2('destroy');
serviceList.remove();
var newServiceInput = '<input type="text" id="service-list" name="services[]" class="form-control">';
parentServiceList.append(newServiceInput);
typeAHead.attr('disabled', true);
email.attr('disabled', true);
phone.attr('disabled', true);
appointmentDetails.attr('disabled', true);
notifications.attr('disabled', true);
} else {
serviceList.remove();
var newServiceSelect = '<select id="service-list" multiple="multiple" class="select2" name="services[]"></select>';
parentServiceList.append(newServiceSelect);
typeAHead.attr('disabled', false);
email.attr('disabled', false);
phone.attr('disabled', false);
appointmentDetails.attr('disabled', false);
notifications.attr('disabled', false);
this.initializeServiceSelect2();
}
}
},
changeFromTime: function(e) {
var text = $(e.currentTarget).text();
$('#timepicker-from').val(text);
this.updateDatesAndTimes();
},
initialize: function () {
var self = this;
var i18n = $.i18n();
var lang = this.$el.find('#lang').val();
$.i18n({locale: lang});
i18n.load(BookyouAdmin.url.i18nFolder, i18n.locale ).done(
function() {
self.successMessage = $.i18n('bookyou-create-success');
self.errorMessage = $.i18n('bookyou-create-error');
self.infoMessage = $.i18n('bookyou-info');
self.unregisteredUser = $.i18n('unregistered-user');
self.initializeClientTypeAHead();
});
var serviceCollection = new ServicesCollection();
serviceCollection.fetch({
success: function (collection, response) {
_.each(collection.models, function (model) {
var element = model.toJSON();
self.services.add(element.services);
self.employees.add(element.employees);
self.employeeServices.add(element.employees_services);
});
self.initializeServiceSelect2();
}
});
this.$el.find('.tp').timeEntry();
},
initializeServiceSelect2: function () {
var self = this;
var list = this.getGeneratedList();
var serviceList = this.$el.find('#service-list');
serviceList.select2({data: list, allowClear: false});
serviceList.on('select2:select', {context: self}, self.getEmployeeList);
},
getGeneratedList: function () {
var self = this;
var list = [];
var categoryList = [];
_.each(self.serviceCategories.models, function (serviceCategory) {
var serviceCategoryModel = serviceCategory.toJSON();
categoryList[serviceCategoryModel.id] = serviceCategoryModel.title;
});
_.each(self.services.models, function (service) {
var serviceModel = service.toJSON();
var categoryTitle = categoryList[serviceModel.cat_id];
var serviceDetails = [];
serviceDetails[serviceModel.id] = serviceModel.title;
if (!(serviceModel.cat_id in list)) {
list[serviceModel.cat_id] = {
id: serviceModel.cat_id,
text: categoryTitle,
children: [{id: serviceModel.id, text: serviceModel.title}]
};
} else {
list[serviceModel.cat_id].children.push({id: serviceModel.id, text: serviceModel.title});
}
});
return list;
},
getEmployeeList: function (e) {
var self = e.data.context;
var employeesSelect = $('select#employee-list:not(.select2-hidden-accessible)');
var servicesSelect = $('#service-list');
var extractIds = function (jQueryObj) {
return _.map(jQueryObj.select2('data'), function (data) {
return data.id;
});
};
var services = extractIds(servicesSelect);
var employees = [];
var employeeServices = self.employeeServices.select(
function (e) {
return (services.indexOf(e.get('service_id').toString()) > -1);
}
);
_.each(employeeServices, function (model) {
var employee = self.employees.get(model.get('employee_id'));
if (employee !== undefined)
employees[model.get('employee_id')] = {
id: model.get('employee_id'),
text: employee.get('first_name') + ' ' + employee.get('last_name')
};
});
var params = {data: _.values(employees)};
//TODO recuring/brigade logic comes here
employeesSelect.select2(params);
employeesSelect.on('select2:select', function () {
self.updateDatesAndTimes();
});
self.updateDatesAndTimes();
},
updateCustomDatesAndTimes: function() {
this.$el.find('#custom-time').val(1);
this.updateDatesAndTimes();
this.$el.find('#custom-time').val(0);
},
updateDatesAndTimes: function () {
var self = this;
var formData = this.$el.find('form').serialize();
$.ajax({
url: BookyouAdmin.url.getAvailableDays,
data: formData,
success: function (data) {
self.setDatesAndTimes(data);
}
});
},
setDatesAndTimes: function (details) {
var dateSettings = details.date_settings;
this.$el.find('#fromDate').val(dateSettings.from.date);
this.$el.find('#toDate').val(dateSettings.to.date);
this.$el.find('#timepicker-from').val(dateSettings.from.time);
this.$el.find('#timepicker-to').val(dateSettings.to.time);
this.setDataToTimePicker(details.from);
},
setDataToTimePicker: function (data) {
var timePickerFrom = this.$el.find('#time-list-from');
var list = '';
for (var i in data) {
var time = data[i].time;
list += '<li role="presentation"><a role="menuitem" class="predefined-from-time" tabindex="-1">' + time + '</a></li>';
}
timePickerFrom.html(list);
},
submitForm: function(e) {
var self = this;
e.preventDefault();
var form = $(e.currentTarget);
var formData = this.$el.find('form').serialize();
$.ajax({
url: BookyouAdmin.url.makeReservation,
data: formData,
type: 'POST',
success: function (data) {
if (data.success == true) {
self.cleanForm(form);
$.get(BookyouAdmin.url.upcomingReservation, function (data) {
self.$el.find("#upcoming_res").html(data);
$.growl.notice({
message: self.successMessage,
title: self.infoMessage
});
});
} else {
$.growl.error({
message: self.errorMessage,
title: self.infoMessage
});
}
},
error: function(data) {
$.growl.error({
message: self.errorMessage,
title: self.infoMessage
});
}
});
},
cleanForm: function(form) {
var serviceSelect = this.$el.find('#service-list');
var employeeSelect = this.$el.find('#employee-list');
serviceSelect.val(null).trigger("change");
employeeSelect.val(null).trigger("change");
this.$el.find('ul.select2-selection__rendered').find('li').remove();
employeeSelect.select2('destroy');
employeeSelect.val('');
employeeSelect.find('option').remove();
form[0].reset();
},
initializeClientTypeAHead: function () {
var self = this;
var suggestClients = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: BookyouAdmin.url.findClient + '?search_field=%QUERY',
wildcard: '%QUERY'
}
});
var clientInput = $('#client-type-a-head');
var readOnly = true;
var message = self.unregisteredUser;
clientInput.typeahead({
minLength: 3,
highlight: true,
}, {
name: 'best-pictures',
display: function (obj) {
return obj.first_name + " " + obj.last_name;
},
source: suggestClients,
templates: {
empty: [
'<div class="empty-message" onclick="$(\'.empty-message\').parent().parent().hide();readOnly = false;">'
+ message+
'</div>',
].join('\n'),
footer:[
'<div class="empty-message" onclick="$(\'.empty-message\').parent().parent().hide();readOnly = false;">'+
message +
'</div>',
].join('\n'),
suggestion:
Handlebars.compile('<div style="cursor:pointer;"><strong>{{first_name}} {{last_name}}</strong>, {{city}}, {{email}}, {{phone}}</div>'),
}
});
clientInput.bind('typeahead:select', function (ev, suggestion) {
var email = $("#email");
var phone = $("#phone");
email.val(suggestion.email);
email.attr('readonly', readOnly);
phone.val((suggestion.phone !== '' && suggestion.phone !== undefined) ? suggestion.phone : suggestion.mobile_phone);
phone.attr('readonly', readOnly);
$('#user_id').val(suggestion.user_id);
});
clientInput.bind('typeahead:render', function (e, data) {
$("#email, #phone").prop("disabled", false);
$("#email, #phone").val('');
$('#user_id').val(0);
});
}
});
BookyouAdmin.base.BookingView = new BookingView();
};
scheduler.config.xml_date='%Y-%m-%d %H:%i';
scheduler.config.first_hour = 0;
scheduler.config.last_hour = 24;
scheduler.config.multi_day = true;
scheduler.config.details_on_create=true;
scheduler.config.details_on_dblclick=true;
scheduler.config.hour_size_px=88;
scheduler.config.displayed_event_color="grey";
scheduler.config.displayed_event_text_color="black";
//scheduler.locale.labels.unit_tab = 'Employee';
scheduler.createTimelineView({
name:"timeline",
x_unit:"minute",//measuring unit of the X-Axis.
x_date:"%H:%i", //date format of the X-Axis
x_step:30, //X-Axis step in 'x_unit's
x_size:24, //X-Axis length specified as the total number of 'x_step's
x_start:16, //X-Axis offset in 'x_unit's
x_length:48, //number of 'x_step's that will be scrolled at a time
y_unit: //sections of the view (titles of Y-Axis)
[{key:1, label:"Section A"},
{key:2, label:"Section B"},
{key:3, label:"Section C"},
{key:4, label:"Section D"}],
y_property:"section_id", //mapped data property
render:"bar" //view mode
});
var shop_id = $('#scheduler_here').data('shop-id');
var loadEmployees = function(shopId) {
$.ajax({
url: 'calendar/default/load-units',
type: 'get',
dataType: 'json',
data: {shop_id: shopId},
success: function(data){
scheduler.createUnitsView({
name: 'unit',
property: 'unit_id', //the mapped data property
list: data //defines the units of the view
});
}
});
};
loadEmployees(shop_id);
scheduler.init('scheduler_here', new Date(),'week');
scheduler.load('calendar/default/load-data?shop_id=' + shop_id, 'json');
var dp = new dataProcessor('calendar/default/load-data?shop_id=' + shop_id);
dp.init(scheduler);
$('#filter-branches').on('change', function(){
scheduler.clearAll();
loadEmployees($(this).val());
$('#scheduler_here').attr('data-shop-id', $(this).val());
scheduler.init('scheduler_here', new Date(), scheduler._mode);
scheduler.load('calendar/default/load-data?shop_id='+$(this).val(), 'json');
});
//initialize the select2
$('#filter-employees').select2();
$('#filter-employees').on('change', function(){
var data = $(this).val();
var list = [];
if (data != null) {
for (var index = 0; index < data.length; ++index) {
list[index] = {key: data[index], label: $(this).find('[value = ' + data[index] + ']').text()};
}
scheduler.createUnitsView({
name: 'unit',
property: 'unit_id', //the mapped data property
list: list //defines the units of the view
});
} else {
loadEmployees($('#filter-branches').val());
}
scheduler.init('scheduler_here', new Date(), 'unit');
scheduler.load('calendar/default/load-data?shop_id='+$(this).val(), 'json');
});
scheduler.attachEvent('onConfirmedBeforeEventDelete', function(id,e){
if (typeof e.id === 'string') {
$.ajax({
url: 'calendar/default/delete-reservation',
type: 'get',
dataType: 'json',
data: {id: id},
success: function(data){
console.log(data);
}
});
}
});
scheduler.attachEvent('onBeforeLightbox', function (id){
console.log(scheduler.getEvent(id));
var currEvent = scheduler.getEvent(id);
if (currEvent) {
if (typeof currEvent.id !== 'string' && (currEvent.readonly || currEvent.start_date < Date.now())) {
scheduler.clearAll();
scheduler.load('calendar/default/load-data?shop_id='+$('#filter-branches').val(), 'json');
return false;
}
}
var shopId = $('#filter-branches').val();
$.ajax({
url: 'calendar/default/quick-booking',
type: 'get',
dataType: 'html',
data: {shop_id: shopId},
success: function(data){
$('#dhx-modal .modal-body').html(data);
$('#dhx_form_save').attr('data-id', id);
$('#dhx-modal').one('shown.bs.modal', function(){
//set dates
$('#fromDate').datepicker('setDate', currEvent.start_date);
$('#timepicker-from').val(moment(currEvent.start_date).format('hh:mm'));
$('#toDate').datepicker('setDate', currEvent.end_date);
$('#timepicker-to').val(moment(currEvent.end_date).format('hh:mm'));
//load data to fields if it exist
if (typeof currEvent.id === 'string') {
$('#service-list').val(currEvent.services).trigger("change").trigger('select2:select');
$('#employee-list').val(currEvent.employee_id).trigger("change").trigger('select2:select');
$('#appointment-details').val(currEvent.comment);
if (currEvent.allDay == 1) {
$('#duration').attr('checked', 'checked').trigger('change');
}
if (currEvent.user_id == 0) {
$('#user_id').val(0);
$('#client-type-a-head').val(currEvent.n_firstname + ' ' + currEvent.n_lastname);
$('#email').val(currEvent.n_email).attr('disabled', 'disabled');
$('#phone').val(currEvent.n_phone).attr('disabled', 'disabled');
} else {
$('#user_id').val(currEvent.user_id);
$('#client-type-a-head').val(currEvent.users.profile.first_name + ' ' + currEvent.users.profile.last_name);
$('#email').val(currEvent.users.email).attr('disabled', 'disabled');
$('#phone').val(currEvent.users.profile.phone).attr('disabled', 'disabled');
}
}
if (currEvent.start_date < Date.now()) {
$('#create-reservation-form select[name], #create-reservation-form input[name], #create-reservation-form textarea, #dhx_form_save').each(function(){
$(this).attr('disabled', 'disabled');
});
}
}).one('hide.bs.modal', function (){
if (typeof currEvent.id !== 'string') {
scheduler.deleteEvent(currEvent.id);
}
}).modal();
//initializing BOOKING FORM BACKBONE VIEW
bookingForm();
bookyou.createDatepickers();
//bookyou.createCustomSelects();
$('select[name=\"time\"]').selectBoxIt({
native: true,
theme : "default",
downArrowIcon: "fa fa-angle-down",
showEffect: "show",
hideEffect: "hide",
showEffectSpeed: 150,
hideEffectSpeed: 150,
autoWidth: false
});
//tinyCheck
$('input[type=radio], input[type=checkbox]').not('.switch').tinyCheck();
},
error: function(e, xhr, settings, except) {
console.log(xhr);
}
});
return false;
});
$('#dhx_form_save').on('click', function() {
var currEvent = scheduler.getEvent($(this).data('id'));
console.log(currEvent);
if (currEvent.start_date < Date.now()) {
return true;
}
var data = {
shop_id: $('#scheduler_here').data('shop-id')
};
$('#create-reservation-form select[name], #create-reservation-form input[name]').each(function(){
data[$(this).attr('name')] = $(this).val();
});
if (typeof currEvent.id === 'string') {
var url = 'calendar/default/update-reservation?id='+currEvent.id;
} else {
var url = 'calendar/default/create-reservation';
}
console.log(data);
$.ajax({
url: url,
type: 'post',
dataType: 'json',
data: data,
success: function(data){
if (data['success']) {
$('#dhx-modal').off('hide.bs.modal').modal('hide');
scheduler.clearAll();
scheduler.init('scheduler_here', new Date(), scheduler._mode);
scheduler.load('calendar/default/load-data?shop_id='+$('#filter-branches').val(), 'json');
} else {
console.log(data);
alert(JSON.stringify(data));
}
},
error: function(e){
console.log(e);
}
});
});
scheduler.attachEvent("onBeforeDrag", function (id, mode, e){
var currEvent = scheduler.getEvent(id);
if (currEvent) {
if (currEvent.readonly || currEvent.start_date < Date.now()) {
return false;
}
}
return true;
});
scheduler.attachEvent("onClick", function (id, e){
var currEvent = scheduler.getEvent(id);
if (currEvent) {
if (currEvent.readonly || currEvent.start_date < Date.now()) {
return false;
}
}
return true;
});
scheduler.attachEvent("onEventLoading", function(ev){
var now = Date.now();
if (ev.start_date < now) {
ev.color = scheduler.config.displayed_event_color;
ev.textColor = scheduler.config.displayed_event_text_color;
}
return true;
});
(function() {
var GameInitialize = function GameInitialize() {
var DEBUG_MODE = false,
GAME_SPEED = 180,
GRAVITY = 1800,
BIRD_FLAP = 550,
PIPE_SPAWN_MIN_INTERVAL = 1200,
PIPE_SPAWN_MAX_INTERVAL = 3000,
AVAILABLE_SPACE_BETWEEN_PIPES = 130,
CLOUD_SPAWN_MIN_TIME = 3000,
CLOUD_SPAWN_MAX_TIME = 10000,
MAX_DIFFICULT = 100,
SCENE = 'game',
TITLE_TEXT = "FLAPPY BIRD",
INSTRUCTIONS_TEXT = "TOUCH\nTO\nFLY",
HIGHSCORE_TITLE = "HIGHSCORES",
HIGHSCORE_SUBMIT = "POST SCORE",
LOADING_TEXT = "LOADING...",
CANVAS_WIDTH = window.innerWidth || document.documentElement.clientWidth || document.getElementsByTagName('body')[0].clientWidth,
CANVAS_HEIGHT = window.innerHeight || document.documentElement.clientHeight || document.getElementsByTagName('body')[0].clientHeight;
if (CANVAS_WIDTH > 720) {
CANVAS_WIDTH = 720;
}
if (CANVAS_HEIGHT > 1280) {
CANVAS_HEIGHT = 1280;
}
var Background,
Clouds, CloudsTimer,
Pipes, PipesTimer, FreeSpacesInPipes,
Bird,
Town,
FlapSound, ScoreSound, HurtSound,
SoundEnabledIcon, SoundDisabledIcon,
TitleText, InstructionsText, DeveloperCopyrightText, GraphicCopyrightText, ScoreText, HighScoreTitleText, HighScoreText, PostScoreText, LoadingText,
PostScoreClickArea,
isScorePosted = false,
isSoundEnabled = true,
Leaderboard;
var gameScore = 0;
//State - BootGame
var BootGameState = new Phaser.State();
BootGameState.create = function() {
LoadingText = Game.add.text(Game.world.width / 2, Game.world.height / 2, LOADING_TEXT, {
font: '32px "Press Start 2P"',
fill: '#FFFFFF',
stroke: '#000000',
strokeThickness: 3,
align: 'center'
});
LoadingText.anchor.setTo(0.5, 0.5);
Game.state.start('Preloader', false, false);
};
//State - Preloader
var PreloaderGameState = new Phaser.State();
PreloaderGameState.preload = function() {
loadAssets();
};
PreloaderGameState.create = function() {
var tween = Game.add.tween(LoadingText).to({
alpha: 0
}, 1000, Phaser.Easing.Linear.None, true);
tween.onComplete.add(function() {
Game.state.start('MainMenu', false, false);
}, this);
};
//State - Main Menu
var MainMenuState = new Phaser.State();
MainMenuState.create = function() {
function click() {
if (Phaser.Rectangle.contains(SoundEnabledIcon.bounds, Game.input.x, Game.input.y)) {
toogleSound();
} else {
birdFlap();
Game.input.onDown.remove(click);
Game.state.start('Game', false, false);
}
}
isScorePosted = false;
createBackground();
createClouds();
createTown();
createPipes(false);
createBird();
createTexts();
createSounds();
gameScore = 0;
Bird.angle = 0;
Bird.reset(Game.world.width / 4, Game.world.height / 2);
Bird.body.allowGravity = false;
Bird.body.gravity.y = 0;
Bird.animations.play('flying');
TitleText.setText(TITLE_TEXT);
DeveloperCopyrightText.setText(DEVELOPER_COPYRIGHT_TEXT);
GraphicCopyrightText.setText(GRAPHIC_COPYRIGHT_TEXT);
InstructionsText.setText(INSTRUCTIONS_TEXT);
ScoreText.setText("");
HighScoreTitleText.setText("");
HighScoreText.setText("");
PostScoreText.setText("");
Game.input.onDown.add(click);
};
MainMenuState.update = function() {
Bird.y = (Game.world.height / 2) + 32 * Math.cos(Game.time.now / 500);
Bird.x = (Game.world.width / 4) + 64 * Math.sin(Game.time.now / 2000);
Town.tilePosition.x -= Game.time.physicsElapsed * GAME_SPEED / 5;
};
//Game state - Where game is going
var GameState = new Phaser.State();
GameState.create = function() {
createPipes(true);
TitleText.setText("");
DeveloperCopyrightText.setText("");
GraphicCopyrightText.setText("");
InstructionsText.setText("");
HighScoreTitleText.setText("");
HighScoreText.setText("");
PostScoreText.setText("");
ScoreText.setText(gameScore);
SoundEnabledIcon.renderable = false;
SoundDisabledIcon.renderable = false;
Bird.body.allowGravity = true;
Bird.body.gravity.y = GRAVITY;
Game.input.onDown.add(birdFlap);
};
GameState.update = function() {
Bird.angle = (90 * (BIRD_FLAP + Bird.body.velocity.y) / BIRD_FLAP) - 180;
if (Bird.angle < -30) {
Bird.angle = -30;
} else if (Bird.angle > 30) {
Bird.angle = 30;
}
Game.physics.overlap(Bird, Pipes, function() {
Game.state.start('GameOver', false, false);
});
if (Bird.body.bottom >= Game.world.bounds.bottom || Bird.body.top <= Game.world.bounds.top) {
Game.state.start('GameOver', false, false);
}
Game.physics.overlap(Bird, FreeSpacesInPipes, addScore);
Town.tilePosition.x -= Game.time.physicsElapsed * getModifiedSpeed() / 5;
};
GameState.render = function() {
if (DEBUG_MODE) {
Game.debug.renderCameraInfo(Game.camera, 32, 32);
Game.debug.renderSpriteBody(Bird);
Game.debug.renderSpriteBounds(Bird);
Game.debug.renderSpriteCorners(Bird, true, true);
Game.debug.renderQuadTree(Game.physics.quadTree);
Pipes.forEachAlive(function(pipe) {
Game.debug.renderSpriteBody(pipe);
Game.debug.renderSpriteCorners(pipe, true, true);
});
FreeSpacesInPipes.forEachAlive(function(spaceInPipe) {
Game.debug.renderSpriteBody(spaceInPipe);
});
}
};
//State which show on Game Over
var GameOverState = new Phaser.State();
GameOverState.create = function() {
getScore();
Game.input.onDown.remove(birdFlap);
setTimeout(function() {
Game.input.onDown.add(HighScoreStateClick);
}, 1000);
if (isSoundEnabled) {
HurtSound.play();
}
Pipes.forEachAlive(function(pipe) {
pipe.body.velocity.x = 0;
});
FreeSpacesInPipes.forEachAlive(function(spaceInPipe) {
spaceInPipe.body.velocity.x = 0;
});
PipesTimer.stop();
TitleText.setText("");
DeveloperCopyrightText.setText("");
GraphicCopyrightText.setText("");
InstructionsText.setText("");
ScoreText.setText("YOUR SCORE: " + gameScore);
PostScoreText.setText(HIGHSCORE_SUBMIT);
HighScoreTitleText.setText(HIGHSCORE_TITLE);
HighScoreText.setText(LOADING_TEXT);
SoundEnabledIcon.renderable = false;
SoundDisabledIcon.renderable = false;
Bird.angle = 180;
Bird.animations.stop();
Bird.frame = 3;
};
//Make bird flap
var birdFlap = function birdFlap() {
Bird.body.velocity.y = -BIRD_FLAP;
if (isSoundEnabled) {
FlapSound.play();
}
};
// Add score to current gameScore
var addScore = function addScore(_, spaceInPipe) {
FreeSpacesInPipes.remove(spaceInPipe);
++gameScore;
ScoreText.setText(gameScore);
if (isSoundEnabled) {
ScoreSound.play();
}
};
//Post score to Clay
var postScore = function postScore() {
if (Leaderboard) {
Leaderboard.post({
score: gameScore
}, function() {
HighScoreText.setText(LOADING_TEXT);
getScore();
});
} else {
HighScoreText.setText('Some error occured');
}
};
//Load Highscores from Clay and render it
var getScore = function getScore() {
if (Leaderboard) {
Leaderboard.fetch({
sort: 'desc',
best: true,
limit: 5
}, function(results) {
if (Game.state.current == 'GameOver') {
var text = "";
for (var i in results) {
if (results.hasOwnProperty(i)) {
text += results[i].rank + '. ' + results[i].name + ' ' + results[i].score + '\n\n';
}
}
HighScoreText.setText(text);
}
});
} else {
HighScoreText.setText('Some error occured');
}
};
var HighScoreStateClick = function HighScoreStateClick() {
if (Game.state.current == 'GameOver' && Phaser.Rectangle.contains(PostScoreClickArea, Game.input.x, Game.input.y) && !isScorePosted) {
postScore();
PostScoreText.setText("");
isScorePosted = true;
} else {
Game.input.onDown.remove(HighScoreStateClick);
Game.state.start('MainMenu', true, false);
}
};
//Get modified GAME_SPEED basic on gameScore
var getModifiedSpeed = function getModifiedSpeed() {
return GAME_SPEED + gameScore * 5;
};
//Toogle sound in game
var toogleSound = function toogleSound() {
if (isSoundEnabled) {
SoundDisabledIcon.renderable = true;
SoundEnabledIcon.renderable = false;
isSoundEnabled = false;
} else {
SoundEnabledIcon.renderable = true;
SoundDisabledIcon.renderable = false;
isSoundEnabled = true;
FlapSound.play();
}
};
//Load assets in game
var loadAssets = function loadAssets() {
Game.load.spritesheet('bird', 'img/bird.png', 48, 35);
Game.load.spritesheet('clouds', 'img/clouds.png', 64, 34);
Game.load.image('town', 'img/town.png');
Game.load.image('pipe', 'img/pipe.png');
Game.load.image('soundOn', 'img/soundOn.png');
Game.load.image('soundOff', 'img/soundOff.png');
Game.load.audio('flap', 'wav/flap.wav');
Game.load.audio('hurt', 'wav/hurt.wav');
Game.load.audio('score', 'wav/score.wav');
};
//Create background
var createBackground = function createBackground() {
Background = Game.add.graphics(0, 0);
Background.beginFill(0x53BECE, 1);
Background.drawRect(0, 0, Game.world.width, Game.world.height);
Background.endFill();
};
//Create clouds
var createClouds = function createClouds() {
function makeNewCloud(cloudX, startTimer) {
cloudX = typeof cloudX == 'undefined' ? Game.world.width : cloudX;
startTimer = typeof startTimer == 'undefined' ? true : false;
var cloudY = Math.random() * Game.world.height / 2,
cloud = Clouds.create(cloudX, cloudY, 'clouds', Math.floor(21 * Math.random())),
cloudScale = 1 + Math.floor((4 * Math.random()));
cloud.alpha = 1 / cloudScale * 2;
cloud.scale.setTo(cloudScale, cloudScale);
cloud.body.allowGravity = false;
cloud.body.velocity.x = -GAME_SPEED / cloudScale * 0.5;
cloud.anchor.setTo(0, 0.5);
cloud.events.onOutOfBounds.add(function(cloud) {
cloud.kill();
});
if (startTimer) {
CloudsTimer.add(Game.rnd.integerInRange(CLOUD_SPAWN_MIN_TIME, CLOUD_SPAWN_MAX_TIME), makeNewCloud, this);
}
}
Clouds = Game.add.group();
var cloudX = 0;
while (cloudX < Game.world.width) {
makeNewCloud(cloudX, false);
cloudX += Math.floor(Math.random() * 100);
}
CloudsTimer = Game.time.create(false);
CloudsTimer.add(0, makeNewCloud, this);
CloudsTimer.start();
};
//Create Fence
var createTown = function createTown() {
Town = Game.add.tileSprite(0, Game.world.height - 128, Game.world.width, 128, 'town');
};
//Create bird
var createBird = function createBird() {
Bird = Game.add.sprite(0, 0, 'bird');
Bird.anchor.setTo(0.5, 0.5);
Bird.animations.add('flying', [0, 1, 2, 3, 2, 1, 0], 20, true);
Bird.animations.play('flying');
Bird.body.collideWorldBounds = true;
Bird.body.gravity.y = 0;
Bird.body.allowGravity = false;
};
//Create Pipes
var createPipes = function createPipes(timer) {
function calcDifficult() {
return AVAILABLE_SPACE_BETWEEN_PIPES + (Math.floor(Math.random() * AVAILABLE_SPACE_BETWEEN_PIPES)) * ((gameScore > MAX_DIFFICULT ? MAX_DIFFICULT : MAX_DIFFICULT - gameScore) / (MAX_DIFFICULT + 1));
}
function makeNewPipe(pipeY, isFlipped) {
var pipe = Pipes.create(Game.world.width, pipeY + (isFlipped ? -calcDifficult() : calcDifficult()) / 2, 'pipe');
pipe.body.allowGravity = false;
pipe.scale.setTo(2.5, isFlipped ? -2 : 2);
pipe.body.offset.y = isFlipped ? -pipe.body.height * 2 : 0;
pipe.body.velocity.x = -getModifiedSpeed();
pipe.events.onOutOfBounds.add(function(pipe) {
pipe.kill();
});
return pipe;
}
function makePipes() {
var pipeY = ((Game.world.height - 16 - calcDifficult() / 2) / 2) + (Math.random() > 0.5 ? -1 : 1) * Math.random() * Game.world.height / 5,
bottomPipe = makeNewPipe(pipeY),
topPipe = makeNewPipe(pipeY, true),
spaceInPipe = FreeSpacesInPipes.create(topPipe.x + topPipe.width, 0);
spaceInPipe.width = 2;
spaceInPipe.height = Game.world.height;
spaceInPipe.body.allowGravity = false;
spaceInPipe.body.velocity.x = -getModifiedSpeed();
var newTime = Game.rnd.integerInRange(PIPE_SPAWN_MIN_INTERVAL, PIPE_SPAWN_MAX_INTERVAL) - getModifiedSpeed() * 2;
PipesTimer.add(newTime < PIPE_SPAWN_MIN_INTERVAL ? PIPE_SPAWN_MIN_INTERVAL : newTime, makePipes, this);
}
if (timer) {
PipesTimer = Game.time.create(false);
PipesTimer.add(0, makePipes, this);
PipesTimer.start();
} else {
Pipes = Game.add.group();
FreeSpacesInPipes = Game.add.group();
}
};
//Create Texts
var createTexts = function createTexts() {
TitleText = Game.add.text(Game.world.width / 2, Game.world.height / 3, TITLE_TEXT, {
font: '32px "Press Start 2P"',
fill: '#FFFFFF',
stroke: '#000000',
strokeThickness: 3,
align: 'center'
});
TitleText.anchor.setTo(0.5, 0.5);
DeveloperCopyrightText = Game.add.text(Game.world.width - 20, Game.world.height - 20, DEVELOPER_COPYRIGHT_TEXT, {
font: '11px "Press Start 2P"',
fill: '#423B30',
stroke: '#FFFFFF',
strokeThickness: 1,
align: 'center'
});
DeveloperCopyrightText.anchor.setTo(1, 1);
GraphicCopyrightText = Game.add.text(20, Game.world.height - 20, GRAPHIC_COPYRIGHT_TEXT, {
font: '11px "Press Start 2P"',
fill: '#423B30',
stroke: '#FFFFFF',
strokeThickness: 1,
align: 'center'
});
GraphicCopyrightText.anchor.setTo(0, 1);
InstructionsText = Game.add.text(Game.world.width / 2, Game.world.height - Game.world.height / 6, INSTRUCTIONS_TEXT, {
font: '16px "Press Start 2P"',
fill: '#FFFFFF',
stroke: '#000000',
strokeThickness: 2,
align: 'center'
});
InstructionsText.anchor.setTo(0.5, 0.5);
ScoreText = Game.add.text(Game.world.width / 2, Game.world.height / 6, "", {
font: '24px "Press Start 2P"',
fill: '#FFFFFF',
stroke: '#000000',
strokeThickness: 3,
align: 'center'
});
ScoreText.anchor.setTo(0.5, 0.5);
HighScoreTitleText = Game.add.text(Game.world.width / 2, Game.world.height / 10, "", {
font: '28px "Press Start 2P"',
fill: '#FFFFFF',
stroke: '#000000',
strokeThickness: 3,
align: 'center'
});
HighScoreTitleText.anchor.setTo(0.5, 0.5);
HighScoreText = Game.add.text(Game.world.width / 2, Game.world.height / 2, "", {
font: '16px "Press Start 2P"',
fill: '#FFFFFF',
stroke: '#000000',
strokeThickness: 2,
align: 'center'
});
HighScoreText.anchor.setTo(0.5, 0.5);
PostScoreText = Game.add.text(Game.world.width / 2, Game.world.height - Game.world.height / 4, "", {
font: '16px "Press Start 2P"',
fill: '#FFFFFF',
stroke: '#000000',
strokeThickness: 2,
align: 'center'
});
PostScoreText.anchor.setTo(0.5, 0.5);
PostScoreClickArea = new Phaser.Rectangle(PostScoreText.x - PostScoreText.width * 5, PostScoreText.y - PostScoreText.height, PostScoreText.width + 200, PostScoreText.height * 4);
};
//Create Sounds
var createSounds = function createSounds() {
SoundEnabledIcon = Game.add.sprite(10, 10, 'soundOn');
SoundEnabledIcon.renderable = isSoundEnabled ? true : false;
SoundDisabledIcon = Game.add.sprite(10, 10, 'soundOff');
SoundDisabledIcon.renderable = isSoundEnabled ? false : true;
FlapSound = Game.add.audio('flap');
ScoreSound = Game.add.audio('score');
HurtSound = Game.add.audio('hurt');
};
//INIT CORE
var Game = new Phaser.Game(CANVAS_WIDTH, CANVAS_HEIGHT, Phaser.CANVAS, SCENE, null, false, false);
Game.state.add('Boot', BootGameState, false);
Game.state.add('Preloader', PreloaderGameState, false);
Game.state.add('MainMenu', MainMenuState, false);
Game.state.add('Game', GameState, false);
Game.state.add('GameOver', GameOverState, false);
Game.state.start('Boot');
Clay.ready(function() {
Leaderboard = new Clay.Leaderboard({
id: 2835
});
});
};
WebFont.load({
google: {
families: ['Press+Start+2P']
},
active: function() {
GameInitialize();
}
});
})();
var game = {
init: function() {
game.settings.keyboard.show();
game.road.trafficLight.setColors();
game.settings.stage.list = $('.traffic-light').map(function(index, element) {
if ($(element).hasClass("tl-red")) {
return {id: index, color: 'red', policeman: game.road.police.setRandom(index)}
} else {
return {id: index, color: 'green', policeman: false}
}
});
},
pedestrian: {
obj: $('.pedestrian'),
intervalId: undefined,
bgPosition: 0,
animate: function () {
this.intervalId = setInterval(function() {
if (game.pedestrian.bgPosition <= -2160) {
game.pedestrian.bgPosition = 0;
} else {
game.pedestrian.bgPosition -= 720;
}
game.pedestrian.obj.css('background-position', "0 ".concat(String(game.pedestrian.bgPosition), 'px'));
if (game.time.current >= 40) {
game.pedestrian.obj.animate({top: '-100px'}, 5000, 'linear');
}
}, 500);
},
stopAnimate: function() {
clearInterval(this.intervalId);
this.obj.stop(true);
}
},
settings: {
isPaused: true,
fps: 60,
handAnimationDuration: 0.5 * this.fps,
keyboard: {
pauseDuration: 6,
show: function() {
if (game.settings.stage.current >= 0 && game.settings.stage.current <= 4 && !game.settings.stage.isFinish) {
$("#question").show();
$(".button-yes, .button-no").one('click', function() {
var msg = game.settings.stage.check($(this).hasClass('button-yes'));
game.settings.display.message(msg);
});
} else {
$("#divKeyboard").show();
$(document).one('keydown click', function(event) {
if (event.type == 'keydown' && event.keyCode == 32 || event.type == 'click') {
game.start();
}
});
}
},
hide: function() {
$("#divKeyboard").css('display', 'none');
$("#question").css('display', 'none');
$(document).off();
}
},
display: {
fadeOn: function() {
$('.lightbox_fadetoblack').css('display', 'block');
},
fadeOff: function() {
$('.lightbox_fadetoblack').css('display', 'none');
},
message: function(msg) {
if (msg) {
$('.good-answer').show();
} else {
$('.bad-answer').show();
}
game.settings.keyboard.hide();
setTimeout(function() {
$("#divKeyboard").show();
$(document).one('keydown click', function(event) {
if (event.type == 'keydown' && event.keyCode == 32 || event.type == 'click') {
$('.good-answer, .bad-answer').hide();
$('#tl-' + game.settings.stage.current).removeClass('tl-red').addClass('tl-green');
game.start();
}
});
}, 500);
}
},
stage: {
list: undefined,
current: undefined,
isFinish: false,
goNext: function() {
this.current++;
},
setTo: function(num) {
this.current = num;
},
check: function(answer) {
if (this.list[this.current].color == 'green') {
if (answer) {
return true;
}
} else if (this.list[this.current].color == 'red') {
if (this.list[this.current].policeman == answer) {
return true;
}
}
return false;
}
},
score: {
total: 0,
win: 0
}
},
start: function() {
if (game.settings.isPaused) {
game.settings.isPaused = false;
if (this.settings.stage.isFinish) {
this.restart();
} else {
this.settings.display.fadeOff();
this.settings.keyboard.hide();
this.pedestrian.animate();
this.street.animate();
this.road.animate();
this.road.traffic.animate();
this.road.trafficLight.animate();
this.time.start();
}
}
},
stop: function() {
if (!game.settings.isPaused) {
game.settings.isPaused = true;
this.time.stop();
this.pedestrian.stopAnimate();
this.street.stopAnimate();
this.road.stopAnimate();
this.road.traffic.stopAnimate();
this.road.trafficLight.stopAnimate();
this.settings.keyboard.show();
this.settings.display.fadeOn();
if (this.settings.stage.isFinish) {
$('#divFinal').show();
}
}
},
restart: function() {
location.reload();
//this.settings.stage.isFinish = false;
//this.time.current = -1;
//this.street.obj.css({top: '-3359px'});
//this.road.obj.css({top: '-3359px'});
//this.road.traffic.clear();
//this.pedestrian.obj.css({top: '460px'});
//this.road.trafficLight.setColors();
},
street: {
obj: $('.street'),
animate: function() {
this.obj.animate({top: 0}, (game.time.total - game.time.stopAt) * 1000, 'linear');
},
stopAnimate: function() {
this.obj.stop(true);
}
},
time: {
obj: $('#p_clock'),
current: -1,
total: 40,
stopAt: 0,
globalIntervalId: undefined,
start: function() {
this.globalIntervalId = setInterval(function() {
game.time.current += 1;
game.time.display();
//cut it to own function
if (game.time.current == 1) {
game.settings.stage.setTo(0);
game.stop();
}
if (game.time.current == 6) {
game.settings.stage.goNext();
game.stop();
}
if (game.time.current == 21) {
game.settings.stage.goNext();
game.stop();
}
if (game.time.current == 33) {
game.settings.stage.goNext();
game.stop();
}
if (game.time.current == 42) {
game.settings.stage.goNext();
game.stop();
}
if (game.time.current == 48) {
game.settings.stage.isFinish = true;
game.stop();
}
//end of function
}, 1000);
},
stop: function() {
this.stopAt = this.current;
clearInterval(this.globalIntervalId);
},
display: function() {
this.obj.text(this.format());
},
format: function() {
var date = new Date(this.current * 1000);
var min = ('0' + date.getMinutes()).slice(-2);
var sec = ('0' + date.getSeconds()).slice(-2);
return min + ':' + sec;
}
},
road: {
obj: $('.car-road'),
animate: function() {
this.obj.animate({top: 0}, (game.time.total - game.time.stopAt) * 1000, 'linear');
},
stopAnimate: function() {
this.obj.stop(true);
},
car: {
color: {
1: 'brown-car',
2: 'green-car',
3: 'red-car',
4: 'blue-car'
},
count: 0,
randomColor: function() {
return this.color[Math.floor(Math.random() * (4 - 1) + 1)];
},
/**
*
* @param prop = {direction, from, to, speed}
*/
create: function(prop) {
game.road.obj.append('<div class="car car'+ this.count +' '+ prop.direction +'"><div class="car-inner '+ game.road.car.randomColor() +'"></div></div>');
$('.car' + this.count).css({top: prop.from}).animate({top: prop.to}, prop.speed, 'linear');
this.count += 1;
}
},
police: {
post: {
0: {left: 800, top: 3629},
1: {left: 1030, top: 3235},
2: {left: 1030, top: 2020},
3: {left: 1030, top: 1054},
4: {left: 807, top: 377}
},
create: function(prop) {
var policeman = $('<div class="policeman"></div>');
policeman.css(prop);
game.road.trafficLight.wrapperObj.append(policeman);
},
setRandom: function(postId) {
if (Math.floor(Math.random() * 2)) {
this.create(this.post[postId]);
return true;
} else {
return false;
}
}
},
trafficLight: {
count: 0,
list: {
1: {top: '270px', left: '1030px'},
2: {},
3: {top: '-120px', left: '530px'}
},
wrapperObj: $('.traffic-light-wrapper'),
getRandomColor: function() {
return Math.floor(Math.random() * 2) == 0 ? 'tl-green' : 'tl-red';
},
setColors: function() {
for (var i = 0; i <=4; i++) {
$('#tl-' + i)
.removeClass('tl-green tl-red')
.addClass(this.getRandomColor());
}
},
animate: function() {
this.wrapperObj.animate({top: '0px'}, (game.time.total - game.time.stopAt) * 1000, 'linear');
},
stopAnimate: function() {
this.wrapperObj.stop(true);
}
},
traffic: {
intervalId: undefined,
animate: function() {
this.intervalId = setInterval(function() {
if (game.time.current == 0) {
game.road.car.create({direction: '', from: '4500px', to: '10000px', speed: 10000});
game.road.car.create({direction: 'reverse', from: '6000px', to: '-500px', speed: 10000});
game.road.car.create({direction: '', from: '8500px', to: '10000px', speed: 8000});
game.road.car.create({direction: 'reverse', from: '8500px', to: '-500px', speed: 10000});
}
if (game.time.current == 7) {
game.road.car.create({direction: '', from: '2000px', to: '10000px', speed: 7000});
game.road.car.create({direction: 'reverse', from: '4500px', to: '-500px', speed: 8500});
game.road.car.create({direction: '', from: '500px', to: '10000px', speed: 10500});
game.road.car.create({direction: 'reverse', from: '6000px', to: '-500px', speed: 8000});
}
if (game.time.current == 12) {
game.road.car.create({direction: '', from: '7500px', to: '10000px', speed: 10000});
game.road.car.create({direction: 'reverse', from: '6000px', to: '-500px', speed: 10000});
game.road.car.create({direction: '', from: '0px', to: '10000px', speed: 8000});
game.road.car.create({direction: 'reverse', from: '8500px', to: '-500px', speed: 11000});
}
if (game.time.current == 19) {
game.road.car.create({direction: '', from: '-500px', to: '10000px', speed: 10000});
game.road.car.create({direction: 'reverse', from: '5000px', to: '-500px', speed: 10000});
game.road.car.create({direction: '', from: '-2000px', to: '10000px', speed: 9500});
game.road.car.create({direction: 'reverse', from: '7500px', to: '-500px', speed: 11500});
}
if (game.time.current == 25) {
game.road.car.create({direction: '', from: '-1000px', to: '10000px', speed: 10000});
game.road.car.create({direction: 'reverse', from: '4000px', to: '-500px', speed: 10000});
game.road.car.create({direction: '', from: '-5500px', to: '10000px', speed: 9500});
game.road.car.create({direction: 'reverse', from: '6500px', to: '-500px', speed: 11500});
}
if (game.time.current == 34) {
game.road.car.create({direction: '', from: '-1000px', to: '10000px', speed: 10000});
game.road.car.create({direction: 'reverse', from: '4000px', to: '-500px', speed: 10000});
game.road.car.create({direction: '', from: '-5500px', to: '10000px', speed: 9500});
game.road.car.create({direction: 'reverse', from: '6500px', to: '-500px', speed: 11500});
}
if (game.time.current == 39) {
game.road.car.create({direction: '', from: '-1000px', to: '10000px', speed: 10000});
game.road.car.create({direction: 'reverse', from: '4000px', to: '-500px', speed: 10000});
game.road.car.create({direction: '', from: '-5500px', to: '10000px', speed: 9500});
game.road.car.create({direction: 'reverse', from: '6500px', to: '-500px', speed: 11500});
}
}, 1000);
},
stopAnimate: function() {
clearInterval(this.intervalId);
},
clear: function() {
$('.car').stop(true);
this.stopAnimate();
game.road.obj.empty();
}
}
}
};
$(document).ready(function () {
game.init();
});
$(document).ready(function ($) {
$('.top_mobile_menu').click(function(event) {
$('.top_mobile_menu_list').toggle();
$('.top_mobile_menu').toggleClass('mobile_menu_active');
// if ($('.top_mobile_menu_list').hasClass('show')) {
// $('.top_mobile_menu_list').toggleClass('show').hide()
// }
// else {
// $('.top_mobile_menu_list').toggleClass('show').show();
// }
});
$('.header_bottom_menu ul.menu li a').removeClass('header_bottom_menu_active');
$('.header_bottom_menu ul.menu li:first a').addClass('header_bottom_menu_active');
// !!!!!!!!! На будушее для карточки товаров
// $(document).on('click', '.item_image_img', function() {
// $(this).siblings('.item_popup').show();
// });
// $(document).on('click', '.item_popup_close', function () {
// $(this).parent().hide();
// });
// Следующее заменить
$(document).on('click', '.item_image_img', function() {
document.location.href = $(this).parent('.item_image').siblings('.product-view').attr('href');
});
//------------------------------------------------------------
$('.top_mobile_menu').click(function (event) {
$('.top_mobile_menu').toggleClass('mobile_menu_active');
if ($('.top_mobile_menu_list').hasClass('show')) {
$('.top_mobile_menu_list').toggleClass('show').hide()
}
else {
$('.top_mobile_menu_list').toggleClass('show').show();
}
});
$('.header_bottom_menu_filter').click(function (event) {
$('.catalog_filter').toggleClass('catalog_filter_active')
$('.header_bottom_menu_filter').toggleClass('header_bottom_menu_filter_active')
});
$('.header_bottom_menu_mobile_category').click(function (event) {
$('.menu').toggle();
$('.catalog_filter').hide();
});
//filter-ajax======================================================================================
$('.header_bottom_menu ul.menu li a').click(function(e){
$('.header_bottom_menu ul.menu li a').removeClass('header_bottom_menu_active');
$(this).addClass('header_bottom_menu_active');
ajaxFilterRequest();
});
$('#sorting').change(function(e){
ajaxFilterRequest();
});
$('.catalog_filter .show-button').on('click', function(e){
ajaxFilterRequest();
});
$('.catalog_filter .clear-button').on('click', function(e){
$('#sorting').val('novelty');
$('#slider-snap-value-lower').html('0');
$('#slider-snap-value-upper').html('8999');
$('.noUi-origin.noUi-connect').css('left', 0);
$('.noUi-origin.noUi-background').css('left', '100%');
$('.color').removeClass('checked');
$('.button-size').removeClass('checked');
$('.productor li').removeClass('checked');
});
function ajaxFilterRequest() {
var url = $('.header_bottom_menu_filter.in_catalog').data('url');
var categoryId = $('.header_bottom_menu ul.menu li a.header_bottom_menu_active').attr('data-id');
var sortBy = $('#sorting').val();
var priceMin = $('#slider-snap-value-lower').html();
var priceMax = $('#slider-snap-value-upper').html();
var colors = [];
var sizes = [];
var producers = [];
$('.color.checked').each(function(e){
colors.push($(this).attr('data-color'));
});
$('.button-size.checked').each(function(e){
sizes.push($(this).attr('data-size'));
});
$('.productor li.checked').each(function(e){
producers.push($(this).attr('data-producer'));
});
$.ajax({
url: url,
type: 'GET',
data: {
categoryId: categoryId,
sortBy: sortBy,
priceMin: priceMin,
priceMax: priceMax,
colors: colors.join(','),
sizes: sizes.join(','),
producers: producers.join(',')
},
success: function(data){
$('.catalog_block').html(JSON.parse(data).html);
window.history.pushState('catalog', 'catalog', JSON.parse(data).url);
console.log(window.history);
}
});
}
$(document).on('click', '.add-to-cart', function(e){
var url = $(this).data('url');
$.ajax({
url: url,
success: function(data){
$('a.basket').append('<div class="alert">'+data+'</div>');
}
});
});
$(document).on('click', '.delete-from-cart', function(e){
var url = $(this).data('url');
$.ajax({
url: url,
success: function(data){
data = JSON.parse(data);
$('a.basket').append('<div class="alert">'+data.count+'</div>');
$('.basket_block_row[data-id="'+data.id+'"]').remove();
}
});
});
$('.basket_num .count').click(function(e){
var count = parseInt($(this).children('span').html());
$(this).children('span').html(count+1);
});
function countCost() {
var commonCost = 0;
$('.order_block_right_title span.cost-with-discount').each(function(){
commonCost += parseInt($('.order_block_right_title span.cost-with-discount').html());
});
$('.order_block_right_title span').html(commonCost);
}
$('.select-size .minus').click(function(e){
$('.select-size .size span').each(function(e){
if (!$(this).hasClass('hidden')) {
$(this).addClass('hidden');
$(this).prev('span').removeClass('hidden');
}
});
});
$('.select-size .plus').click(function(e){
$('.select-size .size span').each(function(indx, elem){
if (!$(elem).hasClass('hidden')) {
$(elem).addClass('hidden');
$(elem).next().removeClass('hidden');
return false;
}
});
});
$('.up_btn').click(function (event) {
window.scrollTo(0, 0)
});
$('.make-order').click(function(e){
var url = $(this).data('url');
var products = [];
$('.basket_block_row:not(.basket_block_row_title)').each(function(indx, elem){
products.push({
'id': $(this).data('id'),
'count': $(this).find('.select-size .count span').html(),
'size': $(this).find('.select-size .size span:not(.hidden)').data('size')
});
});
$.ajax({
type: 'post',
url: url,
data: {
products: products
},
success: function(data){
$('.content').html(data);
}
});
});
$('.basket_block_row img').click(function(){
location.href = $(this).data('url');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment