(function($){

$.findLoadbar = {
	'start': function(){
		var loadbar = $('#find-processing');
		if(loadbar.length === 0) return;
		loadbar.fadeIn('fast');
	},
	'stop': function(){
		var loadbar = $('#find-processing');
		if(loadbar.length === 0) return;
		loadbar.fadeOut('fast');
	}
};

$.rentalFind = {
    show_loading_img: function(){
        $('#result-list').hide();
        $('#waiting_animation').show();
    },

    show_search_results: function(){
        $('#result-list').show();
        $('#waiting_animation').hide();
    },

    validate_date: function(date) {
        if (date.month == 2) {
            if (date.day == 29) {
                if (date.year % 4 != 0 || date.year % 100 == 0 && date.year % 400 != 0) {
                    return false;
                }
            }
            else if (date.day > 28) {
                return false;
            }
        }
        else if (date.month == 4 || date.month == 6 || date.month  == 9 || date.month == 11) {
            if (date.day > 30) {
                return false;
            }
        }
        else {
            if (date.day > 31) {
                return false;
            }
        }

        return true;
    },

    validate: function (submit, initial) {
        var errors = {};
        var validate_result = false;
        var validate_succes = false;
        var valid_pickup_date = true;
        var valid_dropoff_date = true;
        var old_end_depot = $("#id_end_depot").val();
        var old_start_depot = $("#id_start_depot").val();
        var pickup_date = {
            day: $("#id_pickup_date_day").val(),
            month: $("#id_pickup_date_month").val(),
            year: $("#id_pickup_date_year").val()
        };
        pickup_date.date = pickup_date.year + '-' + pickup_date.month + '-' + pickup_date.day;
        var dropoff_date = {
            day: $("#id_dropoff_date_day").val(),
            month: $("#id_dropoff_date_month").val(),
            year: $("#id_dropoff_date_year").val()
        };
        dropoff_date.date = dropoff_date.year + '-' + dropoff_date.month + '-' + dropoff_date.day;

        if (!$.rentalFind.validate_date(pickup_date)) {
            errors['pickup_date'] = '<ul class="errorlist"><li>Incorrect pickup date</li></ul>';
            valid_pickup_date = false;
        }
        if (!$.rentalFind.validate_date(dropoff_date)) {
            errors['dropoff_date'] = '<ul class="errorlist"><li>Incorrect dropoff date</li></ul>';
            valid_dropoff_date = false;
        }

        if (!valid_pickup_date || !valid_dropoff_date) {
            if (!valid_pickup_date) {
                $("#id_pickup_date_day").parents('.field-wrap').find('.errors-container').html(errors['pickup_date']);
            }
            if (!valid_dropoff_date) {
                $("#id_dropoff_date_day").parents('.field-wrap').find('.errors-container').html(errors['dropoff_date']);
            }
        }
        else {
            $.findLoadbar.start();
            $.ajaxq("queue", {
                type: "GET",
                dataType: "jsonp",
                url: rental_config.domain + '/ajax_validate_find_form/?callback=?',
                data: $('#find-form').formSerialize(),
                success: function(data){
                    $.findLoadbar.stop();
                    var errors = data.errors;
                    function getErrorContainer(id) {
                        return $(id).parents('.field-wrap').find('.errors-container');
                    }
                    errors["pickup_date"] = errors["pickup_date"] + errors["__all__"];
                    for (field in errors){
                        if ('__all__' != field) {
                            var id = "#id_" + field;
                            if ('dropoff_date' == field || 'pickup_date' == field) {
                                id = id + '_day'
                            }
                            getErrorContainer(id).html(errors[field]);
                        }
                    }
                    if (data.depot){
                        end_depot = $('#id_end_depot');
                        end_depot.find('optgroup').remove();
                        for (group in data.depot){
                            group = data.depot[group];
                            var optgroup = $('<optgroup label="' + group[0] + '"></optgroup>');
                            for (depot in group[1]) {
                                depot = group[1][depot];
                                optgroup.append('<option value="' + depot["id"] + '">' + depot["name"] + "</option>");
                            }
                            end_depot.append(optgroup);
                        }
                        
                        old_depot_in_new_depots = 0;

                        $("#id_end_depot option").each(function() {
                            if (old_end_depot == this.value) {
                                old_depot_in_new_depots = 1;
                                end_depot.val(old_end_depot);
                                end_depot.trigger('change-value');
                            }
                        });
                        
                        if (old_depot_in_new_depots == 0) {
                            end_depot.val($("#id_start_depot").val());
                            end_depot.trigger('change-value');
                        }

                        // FIXME: It is need?
                        $("#vid_end_depot").attr("value",$("#vid_start_depot").attr("value"));
                    }
                    if (data.start_depot) {
                        start_depot = $('#id_start_depot');
                        start_depot.find('optgroup').remove();
                        for (group in data.start_depot){
                            group = data.start_depot[group];
                            var optgroup = $('<optgroup label="' + group[0] + '"></optgroup>');
                            for (depot in group[1]) {
                                depot = group[1][depot];
                                optgroup.append('<option value="' + depot["id"] + '">' + depot["name"] + "</option>");
                            }
                            start_depot.append(optgroup);
                        }

                        old_depot_in_new_depots = 0;

                        $("#id_start_depot option").each(function() {
                            if (old_start_depot == this.value) {
                                old_depot_in_new_depots = 1;
                                start_depot.val(old_start_depot);
                                start_depot.trigger('change-value');
                            }
                        });
                    }

                    if (data.result == "1"){
                        validate_result=true;
                    }else{
                        validate_result=false;
                    }

                    if (data.date){
                        $('input[name=dropoff_date]').val(data.date).change();
                    }

                    if (submit && validate_result) {
                         if (initial) {
                             $("#is_initial").attr("value", "2");
                         }
                         $("#find-form").submit();
                         $("#is_initial").attr("value", "0");
                    }
                }
            });
        }
    },

    update_filter_by_price_range: function(filter_max) {
        var price_filter = $("#price_range_slider");

        var hid_price_range = $("#id_price_range");
        price_filter.slider('destroy');
        hid_price_range.attr("max", filter_max);

        var find_button_clicked = price_filter.attr('flush_values') == '1';
        if (find_button_clicked) {
            $('#price_range_slider_value2').text(filter_max);
            price_filter.attr('flush_values', '0');
            hid_price_range.attr('value', '0,' + filter_max);
            slider_behavior();
            //FIXME It is need? Commented because not understand;
            //$.rentalFind.validate(true);
        } else {
            slider_behavior();
        }
    }
};


$(document).ready(function(){
    $("#find-form select").bind('change', function() {
        $.rentalFind.validate(false);
    });
    $("#pickup_date select, #dropoff_date select").change(function(){
        var name = $(this).attr('name');
        if (name.match('^pickup_date')) {
            name = 'pickup_date';
        } else {
            name = 'dropoff_date';
        }
        var date = [getDate(name, 'year'), getDate(name, 'month'), getDate(name, 'day')];
        date = date.join('-');
        $('input[name=' + name + ']').val(date);

        function getDate(id, type) {
            var value = $("#id_" + id + "_" + type).val();
            if (1 == value.length) {
                value = '0' + value;
            }
            return value;
        }
    });
});

})(jQuery);

