var search_count = 0;
$(document).ready(function() {
    search_count = $('form.search-form').size();
    for (var i=1; i<=search_count; i++) {
        datePickers(i);
        Rooms.init(i);
        autoFill(i);
    }
});

function datePickers(i) {
    $('#dayin'+i+', #monthin'+i).change(function() {
        var date = $('#monthin'+i).val()+'-'+$('#dayin'+i).val();
        DateFunctions.syncDates(date, 'in', i);
    });
    $('#dayout'+i+', #monthout'+i).change(function() {
        var date = $('#monthout'+i).val()+'-'+$('#dayout'+i).val();
        DateFunctions.syncDates(date, 'out', i);
    });
    var checkin = new Calendar('in', i).init();
    var checkout = new Calendar('out', i).init();
}

DateFunctions = {

	getToday: function() {
	    return (new Date());
	},

    updateDate: function(date, type, i) {
	    if (type == 'out') {
	        date.setUTCDate(date.getUTCDate() + 1);
	    }
	    else {
	        date.setUTCDate(date.getUTCDate() - 1);
	    }
	    var date_day = this.addZero(date.getDate());
	    var month = this.addZero(date.getMonth()+1);
	    var year = this.takeYear(date);
	    var date_month = year+'-'+month;
	    $('#check'+type+'cal'+i).val(date_month+'-'+date_day);
	    $('#day'+type+i).val(date_day);
	    $('#month'+type+i).val(date_month);
	},

    getNextYear: function() {
	    var theDate = new Date();
	    var nextYear = this.takeYear(theDate)+1;
	    var nextMonth = theDate.getMonth();
	    if (nextMonth == 12) {
	        nextMonth = 1; nextYear++;
	    }
	    var nextYearDate = new Date(nextYear, nextMonth);
	    nextYearDate.setDate(nextYearDate.getDate() - 1);
	    return nextYearDate;
	},

	takeYear: function(theDate) {
	    x = theDate.getYear();
	    var y = x % 100;
	    y += (y < 38) ? 2000 : 1900;
	    return y;
	},

	splitDate: function(date) {
	    var parts = [];
	    if (date != '') {
	        parts = date.split('-');
	        for (var i=0; i<parts.length; i++) {
	            parts[i] = parseInt(parts[i].replace(/^0/, ''));
	        }
	    }
	    return parts;
	},

    addZero: function(num) {
        return (num < 10) ? '0'+num : ''+num;
    },

    syncDates: function(date, type, i) {
        if (type == "in") {
            var datein = DateFunctions.splitDate(date);
            datein = new Date(datein[0], datein[1]-1, datein[2]);
            var out = $('#checkoutcal'+i).val();
            if (out == '') {
                DateFunctions.updateDate(datein, 'out', i);
            }
            else {
                dateout = DateFunctions.splitDate(out);
                dateout = new Date(dateout[0], dateout[1]-1, dateout[2]);
                if (datein.getTime() >= dateout.getTime()) {
                    DateFunctions.updateDate(datein, 'out', i);
                }
            }
        }

        if (type == "out") {
            var dateout = DateFunctions.splitDate(date);
            dateout = new Date(dateout[0], dateout[1]-1, dateout[2]);
            var ind = $('#checkincal'+i).val();
            if (ind != '') {
                datein = DateFunctions.splitDate(ind);
                datein = new Date(datein[0], datein[1]-1, datein[2]);
                if (dateout.getTime() <= datein.getTime()) {
                    DateFunctions.updateDate(dateout, 'in', i);
                }
            }
        }

		start = $('#monthin'+i).val() + '-' + $('#dayin'+i).val();
		stop  = $('#monthout'+i).val() + '-' + $('#dayout'+i).val();
        datein = DateFunctions.splitDate(start);
        datein = new Date(datein[0], datein[1]-1, datein[2]);
        dateout = DateFunctions.splitDate(stop);
        dateout = new Date(dateout[0], dateout[1]-1, dateout[2]);

		one_day=1000*60*60*24;
		num_nights = Math.ceil((dateout.getTime()-datein.getTime())/one_day);

		msg = 'Check out'
		if (num_nights > 0) {
			msg += ' (' + num_nights + ' night';
			if (num_nights > 1) {
				msg += 's';
			}
			msg += ')';
		}
        //$('#numNights'+i).html(msg);

    }

}

/**
 * Calendar Class
 * @param {string} type
 * @param {int} i
 * @param {obj} options
 */

var Calendar = function(type, i, options) {

    this.el = $('#check'+type+'cal'+i);
    this.day = $('#day'+type+i);
    this.month = $('#month'+type+i);
    this.i = i;

    var cal = this;

    var defaults = {
        showOn: 'button',
        buttonImage: '/gfx/calendar.gif',
        buttonImageOnly: true,
        dateFormat: 'yy-mm-dd', // YYYY-mm-dd format
        minDate: DateFunctions.getToday(),
        maxDate: DateFunctions.getNextYear(),
        beforeShow: function() {
            cal.el.val(cal.month.val() + '-' + cal.day.val());
            return {};
        },
        onSelect: function(date) {
            cal.month.val(date.substring(0, 7));
            cal.day.val(date.substring(8, 10));
            DateFunctions.syncDates(date, type, i);
        },
		numberOfMonths: 2,
		stepMonths: 2
    };
    $.extend(defaults, options);
    this.config = defaults;
}

Calendar.prototype.init = function() {
    this.el.datepicker(this.config);
}

/**
 * Search Rooms
 * @type {obj}
 */

var Rooms = {

    currentNumRooms: 1,
    i: 0,

    init: function(i) {
        this.i = i;
        this.generateNumRoomSelector();
        this.removeRooms(i);
        this.addRoom(1, i);
    },

    removeRooms: function(num) {
        $('#roomoptions'+num).empty();
    },

    generateNumRoomSelector: function() {
        var values = [];
        var displays = [];
        for (var i=1; i<=WV_MAX_SEARCH_ROOMS+1; i++) {
            var display = (i == WV_MAX_SEARCH_ROOMS+1) ? i+'+' : i;
            values[i-1] = i;
            displays[i-1] = display;
        }
        var html = '<label>number of rooms</label><br />';
        html += this.generateSelect({
            name: 'roomnumber',
            id: 'roomnumber'+this.i,
            cls: 'shortoption',
            tabIndex: 5,
            values: values,
            displays: displays
        });
        $('div.roomnumber'+this.i).append(html);
        var rooms = this;
        $('#roomnumber'+this.i).change(function() {
            if ($(this).val() <= WV_MAX_SEARCH_ROOMS) rooms.currentNumRooms = $(this).val();
            this.currentNumRooms = $(this).val();
            if (!rooms.maxRooms(this)) {
                var i = 1;
                var num = $(this).attr('id').replace('roomnumber', '');
                rooms.removeRooms(num);
                while (i<=WV_MAX_SEARCH_ROOMS && i<= $(this).val()) {
                    rooms.addRoom(i, num);
                    i++;
                }
            }
        });
    },

    addRoom: function(i, num) {
        var html = [
            '<div class="roomtype">',
                '<span>Room '+i+'</span>',
                this.roomPeople(i),
            '</div>'
        ];
        $('#roomoptions'+num).append(html.join(''));
    },

    roomPeople: function(num) {
        var config = {
            name: 'people[]',
            id: 'people_' + this.i + '_' + num
        }
        var values = [];
        var displays = [];
        for (var i=1; i<=4; i++) {
            var val = (i == 4) ? i+'+' : i;
            values[i-1] = val;
            displays[i-1] = val;
        }
        config.values = values;
        config.displays = displays;
        return Rooms.generateSelect(config);
    },

    generateSelect: function(config) {
        var select = '<select name="'+config.name+'"';
        if (config.id != undefined) select += ' id="'+config.id+'"';
        if (config.cls != undefined) select += ' class="'+config.cls+'"';
        if (config.cls != undefined) select += ' tabindex="'+config.tabIndex+'"';
        select += '>';
        for (var i=0; i<config.values.length; i++) {
            select += '<option value="'+config.values[i]+'">'+config.displays[i]+'</option>';
        }
        select += '</select>';
        return select;
    },



    maxRooms: function(select) {

        var dialog_width = 450;
        var dialog_height = 150;

        // only proceed if the final option is selected
        if ($(':selected', select).val() == $('option:last', select).val()) {
            $('#roomnumber'+this.i).val(this.currentNumRooms);
            var div = $('<div>');
            var html = [
                'The maximum number of rooms available to book at one time is 5.',
                'If you would like to book more than 5 rooms please follow the below link to our group booking form:',
                '<br /><br />',
                '<a href="/group-booking.php" onclick="window.location=this.href"; style="font-weight: bold">Group Booking Form</a>'
            ];
            html = html.join(' ');
            div.attr('class', 'ui-dialog');
            div.html(html);
            $('body').append(div);
            $(div).dialog({
                title: 'Group Bookings',
                modal: true,
                width: dialog_width,
                height: dialog_height,
                position: [200, 200],
                resizable: false,
                draggable: false,
                overlay: {
                    opacity: 0.3,
                    background: "black"
                },
                close: function() {
                    if ($.browser.msie) $('#dialog_helper').remove();
                }
            });
            // resize the dialog content as it doesn't size properly
            $('.ui-dialog-content').css('width', (dialog_width-30)+'px').css('height', (dialog_height-60)+'px');

            if ($.browser.msie) {
                // place iframe behind dialog for ie6
                var iframe = $('<iframe>').attr('id', 'dialog_helper').css('width', dialog_width+'px')
                    .css('height', dialog_height+'px')
                    .css('position', 'absolute')
                    .css('top', '200px')
                    .css('left', '200px');
                $('body').append(iframe);
            }
            return true;
        }
        else {
            return false;
        }
    }

}

/**
 * Autofill the form with the last search
 * @param {int} i
 */
function autoFill(i) {
    var search = eval('(' + $.cookie('search') + ')');
    if (search) {

        // dates
        $('#dayin'+i).val(search.dayin);
        $('#monthin'+i).val(search.monthin);
        $('#dayout'+i).val(search.dayout);
        $('#monthout'+i).val(search.monthout);

        // rooms
        if (search.roomnumber) {
            $('#roomnumber'+i).val(search.roomnumber).trigger('change');
        }
        // people per room
        for (var people in search.people) {
            $('#people_'+i+'_'+(parseInt(people)+1)).val(search.people[people]);
        }

        // advanced search
        if ($('#sub'+i).size() > 0) {
            // sublocation
            if (search.sub_location_select) {
                $('#sub'+i).val(search.sub_location_select);
            }

            // star ratings
            if (search.rating) {
                for (var j=0; j<search.rating.length; j++) {
                    $('#rating_1_'+search.rating[j]).attr('checked', 'checked');
                }
            }

            // sort by
            if (search.sortby) {
                $('#sortby'+i).val(search.sortby);
            }
        }

    }
}