﻿(function ($) {
    $.fn.searchControl = function (params) {
        params = $.extend({
            productType: 'Car',
            'pickup': { type: 'airport' },
            'return': { type: 'airport' },
            locationRequired: 'Location is required',
            locationNotFound: 'Location not found',
            invalidPickupDate: 'Invalid pickup date',
            invalidDropoffDate: 'Invalid dropoff date',
            invalidPickupDropoffDate: 'Invalid pickup date and dropoff date',
            optionalText: '(Optioneel)',
            searchingText: 'Please wait...',
            pleaseWaitText: 'Please wait...',
            language: 'en'
        }, params);

        if (params['pickup'].type != 'nearest') params['pickup'].type = 'airport';
        if (params['return'].type != 'nearest') params['return'].type = 'airport';

        this.each(function () {
            var $this = $(this);
            params = $.extend({ element: $this }, params);

            $this.data('searchControl', params);

            $this.find('#select_producttype input[name=producttype]').click(function () {
                $('#pickuplocation_id, #returnlocation_id').val(0);
                $('#pickuplocation_name, #returnlocation_name, #Car_pickuplocation, #Car_returnlocation').val('');

                select($this, this.id.substr('search'.length));
            });

            select($this, params.productType);

            $this
                .find('input.search')
                .add($('#advanced_search_button'))
                .click(function () {
                    submit($this);
                });
        });

        return this;
    };

    function select($el, productType) {
        var params = $el.data('searchControl');
        params.productType = productType;

        $el.find('#select_producttype input').attr('checked', '');
        $el.find('#select_producttype input#search' + productType).attr('checked', 'checked');
        var $searchPanel = $el.find('#producttypes .producttype.search' + productType);
        $searchPanel.parent().children('.producttype').hide();
        $searchPanel.show();

        if (!$searchPanel.data('loaded')) {
            eval('initSearchPanel_' + productType + '($searchPanel, params);');

            $searchPanel.data('loaded', true);
        }

        $el.data('productType', productType);
    }

    var errors = [];

    function submit($el) {
        errors = new Array();
        var params = $el.data('searchControl');
        var productType = $el.data('productType');
        var $productType = $el.find('#producttypes .search' + productType);

        var locations = [productType + '_pickup'];
        if ($el.find('#' + productType + '_oneway')[0].checked) locations.push(productType + '_return');

        var async = [];
        $.each(locations, function (i, v) {
            var type = v.substr(4);
            //if (productType == 'Van') params[type].type = 'nearest';

            if (params[type].type == 'nearest') {
                var $city = $productType.find('#' + v + '_nearest_city');
                if ($city.val() == '') {
                    errors.push($city.attr('title'));
                } else {
                    async.push(v);
                }
            } else {
                if (parseInt($el.find('#' + type + 'location_id').val(), 10) <= 0) {
                    if ($el.find('#' + type + 'location_name').val() != '') {
                        errors.push(params.locationNotFound);
                    } else {
                        errors.push(params.locationRequired);
                    }
                }
            }
        });

        var pickupDate = getDateInSearch("Pickup");
        var dropoffDate = getDateInSearch("Dropoff");
        if (pickupDate < new Date()) {
            errors.push(params.invalidPickupDate);
        }
        if (dropoffDate < new Date()) {
            errors.push(params.invalidDropoffDate);
        }
        if (pickupDate >= dropoffDate) {
            errors.push(params.invalidPickupDropoffDate);
        }

        if (errors.length > 0) {
            alert(errors.join('\n'));
            return false;
        }

        showWaitingPage(params.searchingText);
        if (async.length == 0) {
            return submitAsync(params);
        } else {
            var geocoder = new GClientGeocoder();
            $.each(async, function (i, v) {
                var type = v.substr(4);
                $el.find('#' + type + 'location_id').val(-1);
                var $city = $productType.find('#' + v + '_nearest_city');
                var country = $productType.find('#' + v + '_country option:selected').text();
                if (country == '') country = $productType.find('#' + v + '_country_text').val();
                var countryCode = $productType.find('#' + v + '_country').val();
                var address = $productType.find('#' + v + '_nearest_address').val();
                if (address == params.optionalText) address = '';
                var postal = $productType.find('#' + v + '_nearest_postalcode').val();
                if (postal == params.optionalText) postal = '';

                var fulladdress = '';
                if (address != '') fulladdress = address + ', ';
                if (postal != '') fulladdress += postal + ', ';
                fulladdress += $city.val() + ', ' + country;
                geocoder.getLatLng(
                    fulladdress,
                    function (point) {
                        if (!point) {
                            params.element.find('#' + type + 'location_id').val(0);
                            submitAsync(params);
                        } else {
                            var lat = point.lat().toFixed(5);
                            var lng = point.lng().toFixed(5);
                            $.ajax({
                                url: '/Ajax/GetNearestLocation.ashx',
                                data: { country: country, countryCode: countryCode, city: $city.val(), address: address, postal: postal, lat: lat, lng: lng, language: params.language },
                                success: function (result) {
                                    var $loc = $(result).find('Location');
                                    $('#' + type + 'location_id').val($loc.attr('id'));
                                    $('#' + type + 'location_name').val($loc.attr('name'));
                                    $('#' + type + 'location_type').val($loc.attr('type'));

                                    submitAsync(params);
                                },
                                error: function (e) {
                                    //errors.push(e.statusText);
                                    $('#' + type + 'location_id').val(0);
                                    submitAsync(params);
                                }
                            });
                        }
                    }
                );
            });
        }
    }

    function submitAsync(params) {
        var $el = params.element;
        var pickuplocation = parseInt($el.find('#pickuplocation_id').val(), 10);
        var returnlocation = parseInt($el.find('#returnlocation_id').val(), 10);
        var oneway = $el.find('#' + params.productType + '_oneway')[0].checked;
        if (pickuplocation < 0 || (oneway && returnlocation < 0)) return false;
        if (pickuplocation == 0 || (oneway && returnlocation == 0)) {
            errors.push(params.locationNotFound);
        }

        if (errors.length > 0) {
            hideWaitingPage();
            alert(errors.join('\n'));
            return false;
        }

        var a = $el.find("input, select");
        if ($('#advanced_search').length) {
            a = a.add($('#advanced_search input'));
        }
        a = a.serializeArray();
        var s = [];
        $.each(a, function () {
            s.push(encodeURIComponent(this.name) + "=" + encodeURIComponent(this.value));
        });
        s.push("currency=" + $("#currencies").val());

        $.ajax({
            url: "/select.aspx?ajax=1&" + s.join("&").replace(/%20/g, "+"),
            cache: false,
            success: function () {
                window.location = "/select.aspx";
            }, error: function () {
                window.location = "/select.aspx?" + s.join("&").replace(/%20/g, "+");
            }
        });

        //hideWaitingPage();
        return true;
    }

    function initSearchPanel_Car($panel, params) {
        $.getScript('/lib/js/jquery.autocomplete.min.js', function () {
            $panel.find('#Car_pickuplocation, #Car_returnlocation').autocomplete('/ajax/GetLocations.ashx', {
                extraParams: { language: params.language, service: params.productType },
                minChars: 3,
                max: 60,
                delay: 400,
                width: 340,
                selectFirst: false,
                scroll: false,
                dataType: 'text/html',
                formatItem: formatLocation,
                parse: parseLocation
            }).result(function (event, data) {
                var type = event.target.id == 'Car_pickuplocation' ? 'pickup' : 'return';
                $('#' + type + 'location').val(data[0]);
                $('#' + type + 'location_name').val(data[0]);
                $('#' + type + 'location_id').val(data[1]);
                $('#' + type + 'location_type').val(data[2]);
            });
        });

        $.each(['Car_pickup', 'Car_return'], function (i, v) {
            var type = v.substr(4);

            $panel.find('input[name=' + v + '_type]').click(function () {
                var $this = $(this);
                params[type].type = $this.val();
                var $form = $panel.find('#' + this.id + '_form');
                $form.parent().children('ul').hide();
                $form.show();

                if ($('#' + type + 'location_name').val() != $('#' + v + 'location').val()) {
                    $('#' + type + 'location_id').val(0);
                    $('#' + type + 'location_name').val('');
                }

                if ($this.val() == 'nearest' && !$.data($panel, 'loaded')) {
                    showWaitingPage();
                    $.ajax({
                        url: '/Ajax/GetCountries.ashx',
                        data: { language: params.language },
                        success: function (data) {
                            var $ddl1_selected = $('#Car_pickup_country').val();
                            var $ddl2_selected = $('#Car_return_country').val();
                            var $ddl1 = $('#Car_pickup_country').empty();
                            var $ddl2 = $('#Car_return_country').empty();
                            $.each($(data).find('country'), function (i, e) {
                                $('<option />', { value: $(e).attr('value'), text: $(e).attr('desc') }).appendTo($ddl1);
                                $('<option />', { value: $(e).attr('value'), text: $(e).attr('desc') }).appendTo($ddl2);
                            });
                            $ddl1.val($ddl1_selected);
                            $ddl2.val($ddl2_selected);

                            $.data($panel, 'loaded', true);

                            hideWaitingPage();
                        }, error: function () {
                            hideWaitingPage();
                        }
                    });
                }
            });

            $panel.find('#' + v + '_' + params[type].type).attr('checked', 'checked');
            $panel.find('#' + v + '_' + params[type].type + '_form').parent().children('ul').hide();
            $panel.find('#' + v + '_' + params[type].type + '_form').show();

            $panel.find('#' + v + '_country').blur(function () {
                $panel.find('#' + v + '_country_text').val($(this).find('option:selected').text());
            });
        });

        $panel.find('#' + params.productType + '_oneway').click(function () {
            $panel.find('.return').slideToggle('fast');

            if (!this.checked) {
                params.element.find('#returnlocation_id').val(0);
                params.element.find('#returnlocation_name').val('');
            }
        });
        if (params.oneway) {
            $panel.find('#' + params.productType + '_oneway').attr('checked', 'checked');
            $panel.find('.return').show();
        }

        $panel.find('input.optional').watermark({
            text: params.optionalText
        });
    }

    function initSearchPanel_Van($panel, params) {

        $panel.find('#Van_pickuplocation, #Van_returnlocation').change(function (event) {
            var type = event.target.id == 'Van_pickuplocation' ? 'pickup' : 'return';
            $('#' + type + 'location').val($(this).find('option:selected').text());
            $('#' + type + 'location_name').val($(this).find('option:selected').text());
            $('#' + type + 'location_id').val($(this).val());
            $('#' + type + 'location_type').val('airport');
        });

        $.each(['Van_pickup', 'Van_return'], function (i, v) {
            var type = v.substr(4);

            $panel.find('input[name=' + v + '_type]').click(function () {
                params[type].type = $(this).val();
                $panel.find('#' + this.id + '_form').parent().children('ul').hide();
                $panel.find('#' + this.id + '_form').show();

                if ($('#' + type + 'location_name').val() != $('#' + v + 'location').val()) {
                    $('#' + type + 'location_id').val(0);
                    $('#' + type + 'location_name').val('');
                    $('#' + v + 'location').val(0);
                }
            });

            if ($('#' + type + 'location_id').val() != '') {
                $('#Van_' + type + 'location').children('option[value="' + $('#' + type + 'location_id').val() + '"]')[0].selected = true;
            }

            var locationType = 'airport';
            if (type == 'pickup') {
                if (params.location_id) {
                    var selectedOption = $('#Van_pickuplocation').children('option[value="' + params.location_id + '"]');
                    selectedOption[0].selected = true;
                    $('#pickuplocation_name').val(selectedOption.text());
                    $('#pickuplocation_id').val(params.location_id);
                    $('#pickuplocation_type').val('city');
                }
            }
            $panel.find('#' + v + '_' + locationType).attr('checked', 'checked');
            $panel.find('#' + v + '_' + locationType + '_form').parent().children('ul').hide();
            $panel.find('#' + v + '_' + locationType + '_form').show();

            $panel.find('#' + v + '_country').blur(function () {
                $panel.find('#' + v + '_country_text').val($(this).find('option:selected').text());
            });
        });

        $panel.find('#' + params.productType + '_oneway').click(function () {
            $panel.find('.return').slideToggle('fast');

            if (!this.checked) {
                params.element.find('#returnlocation_id').val(0);
                params.element.find('#returnlocation_name').val('');
            }
        });
        if (params.oneway) {
            $panel.find('#' + params.productType + '_oneway').attr('checked', 'checked');
            $panel.find('.return').show();
        }

        $panel.find('input.optional').watermark({
            text: params.optionalText
        });
    }
})(jQuery);

