$(document).on('mousedown', '.btn', function(event){
event.preventDefault();
var id = parseInt($(this).attr('id').replace('btn_', ''));
click_wait = false;
mousetimer = setTimeout(function(){
click_wait = true;
setTimer(id);
}, 2000);
});
$(document).on('mouseup', '.btn', function(){
clearTimeout(mousetimer);
if (!click_wait){
var id = parseInt($(this).attr('id').replace('btn_', ''));
switchController(id);
console.log('click !!!');
click_wait = false;
}
});
function switchController(id){
var el = $('.btn#btn_' + id);
var state = parseInt($(el).attr('state'));
var need_state;
if (state == 0){
need_state = 1;
} else if (state == 1){
need_state = 0;
}
$(el).addClass('waiting');
$.ajax({
url: 'engine/ajax.php',
type: 'POST',
dataType: 'json',
data: {action: 'setState', id: id, state: state, need_state: need_state},
})
.done(function(data) {
if (data.success == 'ok'){
$(el).attr('state', need_state);
$(el).removeClass('waiting').removeClass('btn_on').removeClass('btn_off');
if(need_state == 1){
$(el).addClass('btn_on');
} else if(need_state == 0){
$(el).addClass('btn_off');
}
}
})
.fail(function(data) {
console.log('error');
});
}
function setTimer(id){
var el = $('.btn#btn_' + id);
var state = parseInt($(el).attr('state'));
var need_state;
if (state == 0){
need_state = 1;
} else if (state == 1){
need_state = 0;
}
$(el).attr('seconds', 0);
$(el).addClass('seconds');
$.ajax({
url: 'engine/ajax.php',
type: 'POST',
dataType: 'json',
data: {action: 'setTimer', id: id, state: state, need_state: need_state},
})
.done(function(data) {
})
.fail(function(data) {
console.log('error');
});
}