/**
 * Created by IOAN on 11/26/2015.
 */
var roomStr = 'Room';

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(){

    var roomRowHtml = '<tr class="roomRow"><td valign="middle" class="roomNum">'+roomStr+' 0</td><td valign="middle"><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 valign="middle"><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 valign="middle" class="childrenAge"></td></tr>';
    var childrenInput = '<input name="age[]" value="" /> ';
    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();

        function showRoomsInfos() {
            var rooms = selectMainRooms.val();
            var adults = selectMainAdults.val();
            var children = selectMainChildren.val();
            if ( ( children > 0 ) || ( rooms > 1 && adults > 4)){
                $("#hotel_form_rooms_infos_container").show(100);
            }
            else
            {
                $("#hotel_form_rooms_infos_container").hide(100);
            }
        }

        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;
                }
            }
        }
    });

    selectMainChildren.off("change");

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

    selectMainRooms.trigger("change");




    /*
     $('#children').change(function(){
     var kids = parseInt($(this).val(), 10);
     console.log(kids);
     if(kids > 0) {

     guests.children = kids;

     $('#extra-rooms').show();
     }
     else {
     $('#extra-rooms').hide();
     }
     });
     */


    // Dates
    $( "#bcheckin" ).datepicker({
        //defaultDate: "+1w",
        minDate: mindate_hotel_search_checkin,
        changeMonth: true,
        numberOfMonths: 2,
        dateFormat: 'dd/mm/yy',
        onClose: function( selectedDate, dtp ) {
            $("#bcheckin, #bcheckout").css({'z-index': '1'});
        },
        onSelect: function( selectedDate, dtp ) {
            $(this).css({'z-index': '9999'});
            var curDate = $(this).datepicker( "getDate" );
            var chekout_min_date = new Date();
            var chekout_max_date = new Date();
            chekout_min_date.setTime(curDate.getTime()+ 1 * 24 * 60 * 60 * 1000);
            chekout_max_date.setTime(curDate.getTime()+ 28 * 24 * 60 * 60 * 1000);

            setTimeout(function(){
                $( "#bcheckout" ).datepicker("show");
            }, 16);

            /*
             console.log(selectedDate);
             console.log(curDate);
             console.log(chekout_min_date);
             console.log(chekout_max_date);
             */

            $( "#bcheckout" ).datepicker( "option", "minDate", chekout_min_date );
            $( "#bcheckout" ).datepicker( "option", "maxDate", chekout_max_date );
        }
    });
    $( "#bcheckout" ).datepicker({
        //defaultDate: "+1w",
        minDate: min_checkout_date,
        maxDate: max_checkout_date,
        changeMonth: true,
        numberOfMonths: 2,
        dateFormat: 'dd/mm/yy',
        onClose: function( selectedDate, dtp ) {
            $("#bcheckin, #bcheckout" ).css({'z-index': '1'});
        },
        onSelect: function( selectedDate, dtp ) {
            $(this).css({'z-index': '9999'});
            //$( "#bcheckin" ).datepicker( "option", "maxDate", selectedDate );
        }
    });

    $('#ui-datepicker-div').wrap('<div class="booking-search"></div>');

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

            if( ok == parseInt($('input[name*=age]').length, 10)) ok = 0;
        }



        if(ok == 0) {
            var $frm = $('#booking-search');
            var hotel_data = $(this).attr('rel') + '|' + ($('#ck-dest').val());
            $.ajax({
                url: full_uri + '/amodules/booking_search/aff/aff_jump.php',
                data: $frm.serialize() + '&current_affiliate=' + hotel_data + '&act=book-hotels',
                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,');
                    }
                }
            });
        }
    });
});