function open_popup(url, win, specs) {
    var new_win = window.open(url, win, specs + "menubar=no,location=no,resizable=yes,scrollbars=yes,status=yes");
}

$(document).ready(function(){

    /*r$.onCondition(function(w) {
        return (w > 200 && w < 1200);
    }).do(function (w) {
        var $box = $('#bbooking-form');
        $box.addClass('box-collapsed');
        $('.btn-box-tool > i', $box).removeClass('fa-minus').addClass('fa-plus');
    });*/

    r$.register('lessThan800',function(w){
        if (w<800) {
            var $box = $('#bbooking-form');
            if($box.data('small') == "") {
                $box.addClass('collapsed-box');
                $('.btn-box-tool > i', $box).removeClass('fa-minus').addClass('fa-plus');
                $box.data('small', 'done');
            }
        }

    });

    r$.start();

    function showRoomsInfos() {
        var selectMainRooms = $("select#main_rooms");
        var selectMainAdults = $("select#main_adults");
        var selectMainChildren = $("select#main_children");

        var rooms = selectMainRooms.val();
        var adults = selectMainAdults.val();
        var children = selectMainChildren.val();

        if ( ( children > 0 ) || ( rooms > 1 && adults > 4)){
            $("#hotel_form_rooms_infos_container").removeClass('hidden');
        }
        else
        {
            $("#hotel_form_rooms_infos_container").addClass('hidden');
        }
    }

    function updateChildAge(childrenSelect) {
        var numChildren = $("td.childrenAge input",childrenSelect.parent().parent()).length;
        var children = childrenSelect.val();
        if ( children > numChildren ) {
            for (i=numChildren; i<children; i++) {
                $("td.childrenAge",childrenSelect.parent().parent()).append(childrenInput);
            }
        }
        else{
            while ( children < numChildren ) {
                $("td.childrenAge input",childrenSelect.parent().parent()).last().remove();
                numChildren = $("td.childrenAge input",childrenSelect.parent().parent()).length;
            }
        }
    }


    // Dynamic datepickers
    $("#bcheckin").datetimepicker({
        useCurrent: true,
        minDate: moment(min_checkin_date, 'DD/MM/YYYY'),
        maxDate: moment(min_checkin_date, 'DD/MM/YYYY').add(6, 'months'),
        viewMode: 'days',
        //format: 'DD/MM',
        showClear: true
    });

    $("#bcheckout").datetimepicker({
        useCurrent: false,
        minDate: moment(min_checkout_date, 'DD/MM/YYYY'),
        maxDate: moment(max_checkout_date, 'DD/MM/YYYY'),
        viewMode: 'days',
        //format: 'DD/MM',
        showClear: true
    });

    $("#bcheckin").on("dp.change",function (e) {
        var c_out = $('#bcheckout').data("DateTimePicker").date();
        if(moment(e.date).isAfter(c_out)) {
            $('#bcheckout').data("DateTimePicker").maxDate(moment(e.date).add(29, 'days'));
            $('#bcheckout').data("DateTimePicker").minDate(e.date);

            $('#bcheckout').data("DateTimePicker").date(moment(e.date));
        }
        else {
            $('#bcheckout').data("DateTimePicker").minDate(e.date);
            $('#bcheckout').data("DateTimePicker").maxDate(moment(e.date).add(29, 'days'));


            $('#bcheckout').data("DateTimePicker").date(moment(e.date));
        }
        $("#bcheckin").data('checkin', moment(e.date).format('YYYY-MM-DD'));
        $("#bcheckout").data('checkout', $('#bcheckout').data("DateTimePicker").date().format('YYYY-MM-DD'));
    });
    $("#bcheckout").on("dp.change",function (e) {
        $("#bcheckout").data('checkout', moment(e.date).format('YYYY-MM-DD'));
    });

    var roomRowHtml = '<tr class="roomRow"><td class="text-center roomNum">'+roomStr+' 0</td><td class="text-center"><select name="group_adults[]"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select></td><td class="text-center"><select name="group_children[]"><option value="0">0</option><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option><option value="10">10</option></select></td><td class="childrenAge"></td></tr>';
    var childrenInput = '<input name="age[]" value="" class="child-age"/> ';
    var selectMainRooms = $("select#main_rooms");
    var selectMainAdults = $("select#main_adults");
    var selectMainChildren = $("select#main_children");
    var roomContainer = $('#hotel_form_rooms_infos');

    selectMainRooms.change(function () {
        var numRooms = $('#hotel_form_rooms_infos tr.roomRow').length;
        var rooms = selectMainRooms.val();
        var adults = selectMainAdults.val();
        var children = selectMainChildren.val();
        var myregexp = new RegExp(eval('/'+roomStr+' [0-9]{1,2}/'));
        var total = 0;
        if ( rooms > numRooms ) {
            for (i=numRooms; i<rooms; i++) {
                roomRowHtml = roomRowHtml.replace(myregexp, roomStr+" " + parseInt(i+1));
                roomContainer.append(roomRowHtml);
            }
        }
        else{
            while ( rooms < numRooms ) {
                roomContainer.find("tr.roomRow").last().remove();
                numRooms = $('#hotel_form_rooms_infos tr.roomRow').length;
            }
        }
        var selectGroupAdults = $("select[name*=group_adults]");
        var selectGroupChildren = $("select[name*=group_children]");

        selectMainAdults.change(function () {
            adults = selectMainAdults.val();
            adultsPerRoom = Math.floor(adults / rooms);
            selectGroupAdults.val(adultsPerRoom);
            adultsPerRoomRest = adults % rooms;
            selectGroupAdults.each(function() {
                if ( adultsPerRoomRest > 0 ) {
                    $(this).val(parseInt($(this).val())+1);
                    adultsPerRoomRest--;
                }
            });
            showRoomsInfos();
        });
        selectMainAdults.trigger("change");
        selectGroupAdults.off("change");
        selectGroupAdults.on("change", function() {
            adults = 0;
            selectGroupAdults.each(function() {
                adults += parseInt($(this).val());
            });
            selectMainAdults.val(adults);
            showRoomsInfos();
        });

        selectGroupChildren.off("change");

        selectGroupChildren.on("change", function() {
            total = 0;
            selectGroupChildren.each(function() {
                total += parseInt($(this).val());
            });
            selectMainChildren.val(total);
            updateChildAge($(this));
            showRoomsInfos();
        });

        selectMainChildren.off("change");

        selectMainChildren.on("change", function() {
            children = selectMainChildren.val();
            childrenPerRoom = Math.floor(children / rooms);
            selectGroupChildren.val(childrenPerRoom);
            childrenPerRoomRest = children % rooms;
            selectGroupChildren.each(function() {
                if ( childrenPerRoomRest > 0 ) {
                    $(this).val(parseInt($(this).val())+1);
                    childrenPerRoomRest--;
                }
                updateChildAge($(this));
            });
            showRoomsInfos();
        });

        selectMainChildren.trigger("change");

        //showRoomsInfos();


    });

    selectMainChildren.off("change");

    selectMainChildren.on("change", function() {
        selectMainRooms.trigger("change");
    });

    selectMainRooms.trigger("change");


    $('.bfind-hotels').on('click',function(e){
        e.preventDefault();
        var $that = $(this);
        var ok = 0;
        var $rooms_infos = $('#hotel_form_rooms_infos');
        if($('input[name*=age]', $rooms_infos).length > 0) {
            $('input[name*=age]', $rooms_infos).each(function(){
                if(parseInt($(this).val(), 10) >=18 || $(this).val() == '' || parseInt($(this).val(), 10) <0) {
                    $(this).css({'border':'2px solid #ff0000'});
                    ok = ok - 1;
                }
                else {
                    $(this).css({'border':'2px solid #73C364'});
                    ok = ok + 1;
                }
            });
        }

        if(ok == parseInt($('input.child-age').length, 10)) {
            var $frm = $('#booking-search');
            var hotel_data = $that.attr('rel') + '|' + ($('#ck-dest').val());
            var params = $frm.serializeJSON();
            params.checkin = moment($("#bcheckin").data('checkin'), 'YYYY-MM-DD').format('DD/MM/YYYY');
            params.checkout = moment($("#bcheckout").data('checkout'), 'YYYY-MM-DD').format('DD/MM/YYYY');
            params.current_affiliate = hotel_data;
            params.act = 'book-hotels';
            console.log(params);
            $.ajax({
                url: submit_search_url,
                data: params,
                async: false,
                cache: false,
                dataType: 'json',
                type: 'post',
                success: function(r) {
                    if(r != null) {
                        open_popup(r.url, r.affiliate, 'left=' + 20 + ',width=' + ($(window).width() -40) + ',height=' + ($(window).height() - 40) + ',top=20,');
                    }
                }
            });
        }
    });


});