$(document).ready(function () {

    //set the seat timer

    try {
        time_left = localStorage.getItem('time_left');
    } catch (err) {
        time_left = timer;
    }

    if (time_left !== null) {
        try {
            min_sec = localStorage.getItem('time_left');
        } catch (err) {
            min_sec = timer;
        }
        $('.timer').html(min_sec);
    } else {
        min_sec = ticketing_timer;
        $('.timer').html(ticketing_timer);
    }
    time_seperate = min_sec.split(':');
    min = time_seperate[0] * 60 * 1000;
    sec = time_seperate[1] * 1000;
    time = min + sec;

    var countDownDate = new Date().getTime() + time;

    if (ticketing_timer_enabled == '1') {
        var x = setInterval(function () {
            var now = new Date().getTime();
            // Find the distance between now an the count down date
            distance = countDownDate - now;

            var min = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            var sec = Math.round((distance % (1000 * 60)) / 1000);

            if (sec == 60) {
                sec = "00";
                min = min + 1;
            }

            if (sec == 00 && min == -1) {
                min = 0;
            }

            if (min.toString().length < 2) {
                min = "0" + min;
            }

            if (sec.toString().length < 2) {
                sec = "0" + sec;
            }

            try {
                localStorage.setItem('time_left', min + ":" + sec);
            } catch (err) {

            }

            $('.timer').html(min + ":" + sec);

            if ($('.timer').html() <= "00:00") {
                clearInterval(x);
                window.location.href = site_url;
            }

        }, 1000);
    }


    //fot the seat plan when page is ready
    fit_plan();
    window.onresize = function (event) {
        //make sure both width & height has changed
        //prevent mobile url bar hide to fire resize
        if ($(window).width() != screenWidth) {
            fit_plan();
            screenWidth = $(window).width();
            screenHeight = $(window).height();
        }
    };

    //when page fully loaded
    window.onload = function () {

        //add pinch handler to seat plan
        function hammerIt(elm) {
            hammertime = new Hammer(elm, {});
            hammertime.get('pinch').set({
                enable: true
            });
            var posX = 0,
                posY = 0,
                transform = "",
                el = elm,
                parent_el = el.parentNode,
                screen = document.querySelector('.screen'),
                wrap = document.querySelector('.seat-wrap');

            hammertime.on('pan pinch panend pinchend', function (ev) {
                //wrap.classList.remove("fitted");
                //pan
                if (scale > fit_scale) {
                    posX = last_posX + ev.deltaX;
                    if (posX > 0) {
                        posX = 0;
                    }
                    if (posX < -max_pos_x) {
                        posX = -max_pos_x;
                    }
                } else {
                    wrap.classList.remove("zoomed");
                    wrap.classList.add("fitted");
                }
                if (posX < -max_pos_x) {
                    //fix problem when zoom out, seat plan stay out of screen
                    transform =
                        "translate(0, 0)" +
                        "scale(" + scale + ")";
                }

                //pinch
                if (ev.type == "pinch") {
                    scale = Math.max(fit_scale, Math.min(last_scale * (ev.scale), 1));
                    screen.style.opacity = 0;
                }
                if (ev.type == "pinchend") {
                    //add class to add right bar for page vertical scroll
                    if (scale > fit_scale) {
                        wrap.classList.remove("fitted");
                        wrap.classList.add("zoomed");
                    } else {
                        wrap.classList.remove("zoomed");
                        wrap.classList.add("zoomed");
                    }
                    last_scale = scale;
                    parent_el.style.height = scale * el.clientHeight + "px";
                    max_pos_x = Math.ceil((scale * el.clientWidth) - parent_el.offsetWidth);
                    screen.style.opacity = 1;
                }

                //panend
                if (ev.type == "panend") {
                    last_posX = posX < max_pos_x ? posX : max_pos_x;
                }

                if (scale > fit_scale) {
                    transform =
                        "translate(" + posX + "px, 0)" +
                        "scale(" + scale + ")";
                }

                //prevent seat plan stay outside screen after pinched
                if (posX < -max_pos_x) {
                    transform =
                        "translate(0, 0)" +
                        "scale(" + scale + ")";
                }

                if (transform) {
                    el.style.webkitTransform = transform;
                }

            });
        }
        hammerIt(document.getElementById("zoom"));

        //set reminder's height
        var wrap = $('#seat-reminder'),
            wrap_height = wrap.height(),
            btn = wrap.find('.solidBtn')
            ;
        wrap.find('.centerContent').css('height', wrap_height);
        $('<div class="overlay"></div>').insertAfter(wrap).velocity('fadeIn');
        wrap.velocity('slideDown');
        btn.one('click', function () {
            $('.overlay').velocity('fadeOut');
                wrap.velocity('slideUp', function () {
                wrap.next('.overlay').remove();
            });
        });

        // Original Source Code FROM designer
        //show custum alert when non-login user clicked next
        // $('.reminder .next').on('click', function () {
        //     $('.overlay').velocity('fadeIn', function () {
        //         $('#cust_alert').show();
        //     });
        //     $('.close').on('click', function () {
        //         $('#cust_alert').remove();
        //         $('.overlay').velocity('fadeOut', function () {
        //             $(this).remove();
        //         });
        //     });
        //     $('#cust_alert .solidBtn').on('click', function () {
        //         window.location.href = 'login.php'
        //     });
        //     $('#cust_alert .strokeBtn').on('click', function () {
        //         window.location.href = 'payment.php'
        //     });
        // });

    }

    $('#time').on('change', function () {

        $('#selected-seat').remove();
        $('#zoom').html("");
        $('#seat-plan').show();
        $('.screen').show();

        var show_id = $('#time').val();

        if (show_id == undefined || show_id == '') {
            seat_message_popup();
            return;
        }

        $.ajax({
            url: site_url + "/seat/changeSeat",
            type: "GET",
            dataType: "JSON",
            data: {
                'show_id': show_id
            },
            cache: false,
            success: function (data) {
                console.log(data);
                $('#zoom').html("");

                if (data.status) {
                    $('input[name="show_id"]').val(show_id);

                    $('#zoom').html(data.seatplan).promise().done(function () {
                        $('#zoom .avai').on('click', pick_seat);
                    });
                    fit_plan();
                    
                    if(cinema_profile == "MACAU"){
                        if(data.houseid == 11){
                            $('#seat-plan').height("340px");
                            $('#zoom').width("430px");
                            $('#zoom').height("360px");
                        }else if(data.houseid == 12){
                            $('#seat-plan').height("548px");
                            $('#zoom').width("777px");
                            $('#zoom').height("548px");
                        }else if(data.houseid == 13){
                            $('#seat-plan').height("450px");
                            $('#zoom').width("450px");
                            $('#zoom').height("460px");
                        }else if(data.houseid == 14){
                            $('#seat-plan').height("420px");
                            $('#zoom').width("420px");
                            $('#zoom').height("420px");
                        }else if(data.houseid == 15){
                            $('#seat-plan').height("420px");
                            $('#zoom').width("420px");
                            $('#zoom').height("410px");
                        }
                    }

                    isLessThan15min = 0;
                    isPass15min = 0;
                    if (data.isLessThan15mnutes) {
                        isLessThan15min = 1;
                    }
                    if (data.isPass15min) {
                        isPass15min = 1;
                    }

                    console.log(isLessThan15min);
                } else {
                    seat_message_popup();
                }
            }
        });
    });

});


function member_login() {

    var email = $("#cust_alert.login input[id='member_email']").val();
    var email_error = $("#cust_alert.login input[id='member_email']").next();

    if (!email_error.hasClass('hide')) {
        email_error.addClass('hide');
    }

    var password = $("#cust_alert.login input[id='member_password']").val();
    var password_error = $("#cust_alert.login input[id='member_password']").next();

    if (!password_error.hasClass('hide')) {
        password_error.addClass('hide');
    }


    if (email == '' || email == undefined || !validEmail(email)) {
        if (email_error.hasClass('hide')) {
            email_error.removeClass('hide');
        }
    }

    if (password == '' || password == undefined) {
        if (password_error.hasClass('hide')) {
            password_error.removeClass('hide');
        }
    }


    if (password != '' && password != undefined && email != '' && email != undefined) {
        var data = {
            'email': email,
            'password': password,
        };


        callAjax('login/seatplan', data, function (result) {
            getCSRF(function (csrf) {
                $("input[name='" + csrf['token_name'] + "']").val(csrf['hash']);
                process();

            }, function (err) {
                alert('ERROR: ON LOGIN');
            });
        }, function (err) {
            if (err['error'] != undefined) {
                if (err['error']['password'] != undefined) {
                    var password_error = $("#cust_alert.login input[id='member_password']").next();

                    if (password_error.hasClass('hide')) {
                        password_error.removeClass('hide');
                    }
                }

                if (err['error']['email'] != undefined) {
                    var email_error = $("#cust_alert.login input[id='member_email']").next();
                    if (email_error.hasClass('hide')) {
                        email_error.removeClass('hide');
                    }
                }
            } else {
                alert('ERROR: ON LOGIN');
            }
        });
    }


}

function non_guest_login() {
    getCSRF(function (csrf) {
        $("input[name='" + csrf['token_name'] + "']").val(csrf['hash']);
        process();

    }, function (err) {
        alert('ERROR: ON LOGIN');
    });
}


function process() {

    if (checkSeatPlan()) {
        var btn = $(this);

        btn.attr('disabled', 'disabled');

        var seats = [];
        $('.avai.picked').each(function (i, ele) {
            var seatSelect = $(ele).data('name');
            seats.push(seatSelect);
        }).promise().done(function () {

            $('input[name="seats"]').val('');

            if (seats.length > 0) {
                var str_seat = seats.toString();
                $('input[name="seats"]').val(str_seat);
                $('input[name="timer"]').val($('.timer').html());
                $('form[name="hidden_form"]').submit();

            } else {
                btn.removeAttr('disabled');
            }

        });
    } else {
        console.log('Failed');
        $('.overlay').velocity('fadeIn', function () {
            $('#cust_alert.seat_selection_message').show();
        });
        $('.close').on('click', function () {
            $('#cust_alert.seat_selection_message').hide();
            $('.overlay').velocity('fadeOut', function () {
                // $(this).remove();
            });
        });
        $('#cust_alert.seat_selection_message .solidBtn').on('click', function () {
            $('#cust_alert.seat_selection_message').hide();
            $('.overlay').velocity('fadeOut', function () {
                // $(this).remove();
            });
        });
    }
}

//fit the seat plan fn
function fit_plan() {
    var wrap = document.querySelector('.seat-wrap');
    wrap.classList.remove("zoomed");

    var stage = document.getElementById("seat-plan"),
        plan = document.getElementById("zoom"),
        plan_width = plan.offsetWidth,
        scaleX = stage.offsetWidth / plan_width,
        scale_floor = Math.floor(scaleX * 100) / 100,
        scale_final = Math.min(scale_floor, max_scale)
        ;

    wrap.classList.add("fitted");

    //update fit_scale & scale plan
    fit_scale = scale = last_scale = scale_final;
    last_posX = 0;
    last_posY = 0;
    max_pos_x = 0;

    plan.style.transform = ('scale(' + scale_final + ')');

    //set parent's height
    stage.style.height = scale_final * plan.clientHeight + "px";

    //set parent's text-align
    stage.style.textAlign = 'center';
}

function seat_message_popup() {
    $('.overlay').velocity('fadeIn', function () {
        $('#cust_alert.show_select_message').show();
    });
    $('.close').on('click', function () {
        $('#cust_alert.show_select_message').hide();
        $('.overlay').velocity('fadeOut', function () {
            // $(this).remove();
        });
    });
    $('#cust_alert.show_select_message .solidBtn').on('click', function () {
        $('#cust_alert.show_select_message').hide();
        $('.overlay').velocity('fadeOut', function () {
            // $(this).remove();
        });
    });
}


function wheelchair_message_popup() {
    $('.overlay').velocity('fadeIn', function () {
        $('#cust_alert.show_wheelchair_message').show();
    });
    $('.close').on('click', function () {
        $('#cust_alert.show_wheelchair_message').hide();
        $('.overlay').velocity('fadeOut', function () {
            // $(this).remove();
        });
    });
    $('#cust_alert.show_wheelchair_message .solidBtn').on('click', function () {
        $('#cust_alert.show_wheelchair_message').hide();
        $('.overlay').velocity('fadeOut', function () {
            // $(this).remove();
        });
    });
}


function checkSeatPlan() {
    var accept_counter = 0;
    var reject_counter = 0;
    buyable = true;
    seat_regex_array = [];
    var get_seatplan_seat = "";

    for (var i = 1; i <= max_row; i++) {
        seat_regex = '';
        if(cinema_profile == "MACAU"){
            get_seatplan_seat = "#seat-plan div span";
        }
        else{
            get_seatplan_seat = "#seat-plan div div span";
        }
        $(get_seatplan_seat).each(function (index) {
            var span_row = $(this).data('row');
            var regex_code = '0';

            if ($(this).is('.space')) {
                return true;
            }

            if (span_row == i) {
                if ($(this).is('.correridor, .row-label, .processing, .sold, .reserved, .wheelchair, .prog')) {
                    regex_code = '2';
                } else if ($(this).hasClass('picked')) {
                    regex_code = '1';
                } else if ($(this).hasClass('avai') && !($(this).hasClass('picked'))) {
                    regex_code = '0';
                } else if ($(this).hasClass('twin-gap')) {
                    return true;
                }
                seat_regex += regex_code;
            }
        });
        seat_regex_array.push("2"+seat_regex+"2");
    }

    console.log(reject_list);
    console.log(seat_regex_array);

    var tmp_loop = true;
    var reject_code_total = 0;
    var accept_code_total = 0;

    $.each(seat_regex_array, function (index, value) {
        var re = /0{1}/g;

        // console.log(value.match(re));
        
        var match = value.match(re);


        if (match != undefined && match.length == 1) {
            buyable = true;
            return true;
        }

        $.each(reject_list, function (index, reject_code) {
            reject_counter = 0;
            if (value.indexOf(reject_code) !== -1) {
                buyable = false;
                reject_counter++;
                var tmp_reject_code = new RegExp('(?=((' + reject_code + ')))\\d', 'g');
                reject_code_total = (value.match(tmp_reject_code) || []).length;
            }

            accept_counter = 0;
            if (!buyable) {
                $.each(accept_list, function (index, accept_code) {
                    if (value.indexOf(accept_code) !== -1 && accept_code.indexOf(reject_code) !== -1) {
                        buyable = true;
                        accept_counter++;

                        var tmp_accept_code = new RegExp('(?=((' + accept_code + ')))\\d', 'g');
                        accept_code_total = (value.match(tmp_accept_code) || []).length;

                        if (accept_code_total != reject_code_total) {
                            return false;
                        }
                    }
                });
            }

            if ((reject_counter > accept_counter && accept_counter == 0) || (accept_code_total != reject_code_total)) {
                tmp_loop == false;
                return false;
            }
        });

        if (!tmp_loop) {
            return false;
        }
    });

    if (!tmp_loop) {
        return false;
    } else {
        return buyable;
    }

}