
var modalCloseTimeOut = null;

//to open table event
$('.theType').live('change', function () {
    var val = $('input:radio[name="theType"]:checked').val();
    if (val == 0) {
        $('#reservationTime').hide();
    } else {
        $('#reservationTime').show();
    }
});
$('.openPlayStation').live('click', function () {
    var thisis = $(this);
    var sui = $('#sui').val();
    $.ajax({
        type: 'POST',
        url: 'dailyentryajax.php?do=cksession',
        data: {sui: sui},
        success: function (data) {
            if (data == 1) {
                $('#openPSid').val(thisis.data('id'));
                //
                $('#theType0').attr('checked', 'checked').change();
                $('#hoursResrvation').val("");
                $('#minutesResrvation').val("");
                //
                $('#openPlayModalTitle').html("حجز " + $('li[data-id="' + thisis.data('id') + '"]').first().data('name'));
                $('#openPlayModal').modal('show');
            } else if (data == -1) {
                alert('sorry,session ended you have to login again');
                window.location.href = 'logout.php';
            }
        }
    });

});
$('#startReservation').live('click', function () {
    if (!$('#startReservation').hasClass('processing...')) {
        $('#startReservation').addClass('processing...');
        //console.log($('#startReservation').hasClass('processing...'));
        var val = $('input:radio[name="theType"]:checked').val();
        if (val == "1" && Number($('#hoursResrvation').val()) == 0 && Number($('#minutesResrvation').val()) == 0) {
            $('#hoursResrvation').css('background-color', 'yellow');
            $('#minutesResrvation').css('background-color', 'yellow');
            $('#startReservation').removeClass('processing...');
            return false; //dont continue
        } else {
            $('#hoursResrvation').css('background-color:white');
            $('#minutesResrvation').css('background-color:white');
        }

        openPlayStation($('#ps' + $('#openPSid').val()));
    }

});
$('.closePlayStation').live('click', function () {
    //$('#modal').modal('show');
    // alert("ss");
    getCloseData($(this));
    //closePlayStation($(this));
});

/*-- end buttons click ---------------------------------------------------------*/
$('.endbill').live('click', function () {

    if (!$(this).hasClass('processing...')) {
        $('.endbill').addClass('processing...');
        $('#printBill').val($(this).data('print'));
        $('#endRestaurantTable').val($(this).data('end-restaurant-table'));

        //console.log($('#deviceIdentification').val());
        //console.log($('#subDeviceIdentification').val());
        try {

            switchOFF($('#subDeviceIdentification').val(), $('#deviceIdentification').val(), $('#psid').val())

        } catch (err) {
        }
        if (Number($('#client').val()) > 0) {
            //do nothing
        } else {
            $('#payed').val($('#netPrice').val());
        }
        $('#endPlayInfo').submit();
    }


});
/*----------------------------------------------------------------------------*/

function openPlayStation(thisis) {
    // document.getElementById("hazem32").value="ddddddd";
    // alert("s");

    if (!thisis.hasClass('processing...')) {
        thisis.addClass('processing...');
        var id = thisis.data('id');
        var theType = $('input:radio[name="theType"]:checked').val();
        var priceIs = Number($('input:radio[name="priceIs"]:checked').val());
        $.ajax({
            type: 'POST',
            url: 'restaurantplaystationpalyajax.php?do=openPlayStation',
            data: {id: id, theType: theType, hoursResrvation: $('#hoursResrvation').val(), minutesResrvation: $('#minutesResrvation').val(), priceIs: priceIs},
            //async: false,
            success: function (data) {
                data = JSON.parse(data);
                //console.log("dta===>>>>", data);
                try {
                    switchon(thisis.data('subIdentification'), thisis.data('identification'));
                } catch (err) {
                    // document.getElementById("demo").innerHTML = err.message;
                }
                //
                var oldsrc = $('#img' + id).attr('src');
                var newsrc = oldsrc.split("/");
                newsrc[6] = "ps-active.png";
                $('#img' + id).attr('src', newsrc.join('/'));
                //
                $('#title' + id).html(thisis.data('name'));
                $('#startTime' + id).html(data.start);
                $('li[data-id="' + id + '"]').first().data('beingused', 1);
                $('li[data-id="' + id + '"]').first().data('type', theType);
                $('li[data-id="' + id + '"]').first().data('end', data.end);
                $('li[data-id="' + id + '"]').first().data('priceis', priceIs);
                $('#priceIs' + id).text(data.hourPrice);


                if (theType == 0) {
                    $('#timerImage' + id).hide();
                } else {
                    $('#timerImage' + id).show();
                }

                if (priceIs == 1) {
                    $('#multiImage' + id).show();
                } else {
                    $('#multiImage' + id).hide();
                }

                thisis.removeClass('openPlayStation');
                thisis.removeClass('statusIsClosed');
                thisis.addClass('closePlayStation');
                thisis.addClass('statusIsOpen');
                thisis.removeClass('processing...');


                $('#openPlayModal').modal('hide');
                //////////
                if (theType == 1) {
                    var timerName = "psTimer" + id;
                    // Update the count down every 1 second
                    timerName = setInterval(function () {
                        var retData = calTimerRemainingDistance(data.end);
                        handleTimerRemainingData(retData, timerName, id, thisis.data('subIdentification'), thisis.data('identification'));
                        // switchOFF(thisis.data('subIdentification') ,thisis.data('identification'))

                    }, 1000);
                }
                //give time for modal to close to avoid multi clicking that we stop with class
                $('#startReservation').removeClass('processing...');

            }
        });
    }
}
function getCloseData(thisis) {
    if (!thisis.hasClass('processing...')) {
        thisis.addClass('processing...');
        var id = thisis.data('id');
        $.ajax({
            type: 'POST',
            url: 'restaurantplaystationpalyajax.php?do=getCloseData',
            data: {id: id},
            async: false,
            success: function (data) {
                // switchOFF(thisis.data('subIdentification'),thisis.data('identification'));
                thisis.removeClass('processing...');
                if (data == "sessionEnded!") {
                    alert('sorry,session ended you have to login again');
                    window.location.href = 'logout.php';
                } else {
                    $('#endPlayInfo').html(data);
                    if (Number($('#playstationTableId').val()) > 0) {
                        $('#endbillAndRestaurantTableandprint').show();
                    } else {
                        $('#endbillAndRestaurantTableandprint').hide();
                    }
                    $('#endbillWithCard').attr('href', 'playStationCardController.php?do=payCard&id=' + id);
                    $('#endPlayModal').modal('show');
                    clearModalCloseTimeOutFunc();
                    modalCloseTimeOutFunc();
                }
            }
        });
    }
}

function modalCloseTimeOutFunc() {
    modalCloseTimeOut = setTimeout(function () {
        $('#endPlayModal').modal('hide');
    }, 1000 * 60 * 5);
}
function clearModalCloseTimeOutFunc() {
    clearTimeout(modalCloseTimeOut);
}
function calTimerRemainingDistance(countDownDate) {
    countDownDate = new Date(countDownDate).getTime();
    // Get today's date and time
    var now = new Date().getTime();

    // Find the distance between now and the count down date
    var distance = countDownDate - now;

    // Time calculations for days, hours, minutes and seconds
    var days = Math.floor(distance / (1000 * 60 * 60 * 24));
    var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
    var seconds = Math.floor((distance % (1000 * 60)) / 1000);

    var retData = {distance: distance, days: days, hours: hours, minutes: minutes, seconds: seconds};
    return retData;
}
function handleTimerRemainingData(timeRemaingngData, timerName, id, sub, main) {
    // If the count down is finished, write some text
    if (timeRemaingngData.distance < 0) {
        switchOFF(sub, main, id);

        clearInterval(timerName);
        $('#timer' + id).text("EXPIRED");
        $('#ps' + id).children('a').first().addClass("dangerBorder");
        var snd = new Audio("../views/default/assets/sounds/timeout.mp3"); // buffers automatically when created
        snd.play();
        //normal alert witll pause js execution which is bad in user experience for a timer so we do it this way
        //bootstarp modal created on the fly
        var popupTemplate =
                '<div class="modal fade">' +
                '  <div class="modal-dialog modal-sm">' +
                '    <div class="modal-content">' +
                '      <div class="modal-header">' +
                '        <button type="button" class="close" data-dismiss="modal">&times;</button>' +
                '        <h4 class="modal-title">تنبيه</h4>' +
                '      </div>' +
                '      <div class="modal-body" style="overflow-y: hidden;">' +
                '           وقت ' + $('li[data-id="' + id + '"]').first().data('name') + ' انتهى' +
                '      </div>' +
                '      <div class="modal-footer">' +
                '        <button type="button" class="btn btn-primary" data-dismiss="modal">ok</button>' +
                '        <!--button type="button" class="btn btn-link" data-dismiss="modal">Cancel</button-->' +
                '      </div>' +
                '    </div>' +
                '  </div>' +
                '</div>';

        $(popupTemplate).modal()

    } else {
        // Display the result in the element
        $('#timer' + id).text(timeRemaingngData.hours + "h " + timeRemaingngData.minutes + "m " + timeRemaingngData.seconds + "s ");
    }
}
/*-----------------------------------------------------------
 function printKitchen(tableId, printNow) {
 $.ajax({
 type: 'POST',
 url: 'sellbillAjaxController.php?do=printKitchen',
 data: {tableId: tableId},
 async: false,
 success: function (data) {
 if (data != -1) {
 if (printNow == 1)
 {
 $('#printPlaystationPlayDiv').html(data);
 setTimeout(function () {
 printContent('printPlaystationPlayDiv');
 $('#printPlaystationPlayDiv').html("");
 }, 1000);
 }
 }

 getOrderDetails(tableId);
 }
 });
 }*/
function printContent(el) {
    // alert("s

    var restorepage = document.body.innerHTML;
    var printcontent = document.getElementById(el).innerHTML;
    document.body.innerHTML = printcontent;
    print_Custom('mycustomheader');
    document.body.innerHTML = restorepage;
}

$('.movePS').live('click', function () {
    $('#movePlayModal').modal('show');
});
$('#movePSNow').live('click', function () {
    if (!$(this).hasClass('processing...')) {
        $(this).addClass('processing...');
        var fromDevice = Number($('#fromDevice').val());
        var toDevice = Number($('#toDevice').val());

        var oldFromDevicePriceIs = Number($('#ps' + fromDevice).data('priceis'));
        var newFromDevicePriceIs = Number($('input:radio[name="newFromDevicePriceIs"]:checked').val());

        if ((fromDevice > 0 && toDevice > 0) || (fromDevice > 0 && oldFromDevicePriceIs != newFromDevicePriceIs)) {
            $('#movePlayInfo').submit();
        } else {
            alert('لابد من اختيار من والى او تغيير الحجز');
            $(this).removeClass('processing...');
        }
    }
});
$("#fromDevice").select2({
    dropdownParent: $('#movePlayModal'), //to avoid hiding options behind modal//not working
    placeholder: "نقل من",
    minimumInputLength: 0,
    //  minimumInputLength: 3,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "restaurantplaystationpalyajax.php?do=getdevicesfrom",
        dataType: 'json',
        data: function (term, page) {
            //  alert(term);
            return {
                term: term, //search term
                page_limit: 10, // page size
            };
        },
        results: function (data) {
            // alert(term);
            return {results: data};
        }
    },
    formatResult: function (data) {
        return  data.text;
    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
        var data = {id: item[0], text: item[1]};
        callback(data);
    }
}).on('change', function () {
    var fromDevice = Number($('#fromDevice').val());
    var oldFromDevicePriceIs = Number($('#ps' + fromDevice).data('priceis'));
    $('#newFromDevicePriceIs' + oldFromDevicePriceIs).attr('checked', 'checked');
    $('#oldFromDevicePriceIs').val(oldFromDevicePriceIs);
});
$("#toDevice").select2({
    dropdownParent: $('#movePlayModal'), //to avoid hiding options behind modal//not working
    placeholder: "نقل الى",
    minimumInputLength: 0,
    //  minimumInputLength: 3,
    multiple: false,
    quietMillis: 100,
    ajax: {
        url: "restaurantplaystationpalyajax.php?do=getdevicesto",
        dataType: 'json',
        data: function (term, page) {
            //  alert(term);
            return {
                term: term, //search term
                page_limit: 10, // page size
            };
        },
        results: function (data) {
            // alert(term);
            return {results: data};
        }
    },
    formatResult: function (data) {
        return  data.text;
    },
    initSelection: function (element, callback) {
        var item = element.val().split(':');
        var data = {id: item[0], text: item[1]};
        callback(data);
    }
});

$(document).ready(function () {

    $('#allPlaystationsUL li').each(function () {
        // test1();
        var thisis = $(this);
        var id = thisis.data('id');
        //console.log(id)
        //console.log(thisis);
        // setTimeout(function(){
        // sub(thisis.data('subIdentification') ,thisis.data('identification'));

        // }, 1000);


// console.log(thisis.data('identification'));
// console.log(thisis.data('subIdentification'));

        // alert( thisis.data('deviceIdentification'));
        // alert(document.getElementById("hazem32").value);
        var beingused = thisis.data('beingused');
        var type = thisis.data('type');
        var end = thisis.data('end');
        if (beingused == 1 && type == 1) {
            var timerName = "psTimer" + id;
            // Update the count down every 1 second
            timerName = setInterval(function () {
                var retData = calTimerRemainingDistance(end);
                handleTimerRemainingData(retData, timerName, id, thisis.data('subIdentification'), thisis.data('identification'));
            }, 1000);
        }
    });
});
$(document).ready(function () {
    // 	if(window.innerHeight > window.innerWidth){
// 		alert("window.innerHeight > window.innerWidth");
//     alert("Please use Landscape!");
// }
    if (window.innerHeight > window.innerWidth) {
        alert("This page is best viewed in landscape mode,please rotate your Screen");
    }

// $('.add-table').click(function(){
// 	$("#add-table").css('display','block');
// })

});
$(document).ready(function () {
    if ($('#printPlaystationPlay').length > 0 && Number($('#printPlaystationPlay').val()) > 0) {
        var printPlaystationPlayOrderId = Number($('#printPlaystationPlayOrderId').val());
        window.open("sellbillprintController.php?do=showDetail2&id=" + Number($('#printPlaystationPlay').val()) + "&ordertype=0&playstation=1&psOrder=" + printPlaystationPlayOrderId);
    }
});
