Interface.search = {
    defaultPointsCount : 0,
    // works for big map too
    maxPointsCount     : 10000,

    check: function(length) {
        if (!length) {
            length = 28;
        }

        // Bind action to drop down
        FadeCheck.bind('fade_type', 'open', function(){
            $('#fade_specail_wishes').parent('div').css('display','none');
        });

        FadeCheck.bind('fade_type', 'close', function(){
            $('#fade_specail_wishes').parent('div').fadeIn('slow');
        });

        FadeCheck.titleParams.length = length;
    },

    index: {
        bNeedToShowForm: false,
        request:         '',
        sort:            '',
        direction:       '',
        per_page:        0,
        limit:           0,
        url:             '',

        allPoints : false,
        link      : '',

        button: {
            object: '',
            selector: '#mini-map-postload a',

            init: function() {
                Interface.search.index.button.object = $(Interface.search.index.button.selector);
            },

            destroy: function() {
                if (Interface.search.index.button.isExist) {
                    Interface.search.index.object.remove();
                }
            },

            isExist: function() {
                return 1 == $(Interface.search.index.button.selector).length;
            },

            show: function() {
                Interface.search.index.button.object.show();
            },

            hide: function() {
                Interface.search.index.button.object.hide();
            }
        },

        center: {
            lat:  41.87194,
            lng:  12.56738,
            zoom: 5
        },

        init: function() {
            $('a#show_big_map').click(function(){
                Interface.search.index.toggleMap(this);
                return false;
            });
            
            // Load search form
            if(Interface.search.index.bNeedToShowForm) {
                Interface.search.index.toggleSearchForm();

                // Don`t show close form button, if there no element on page
                $('div.close-search-container').hide();
            }

            // Set main image for search thumb
            $('.search_thumb').click(function(){
                $(this).parents('div.item').find('img.main').attr('src',$(this).attr('longdesc'));
            });

            $('select[name="per_page"]').val(Interface.search.index.per_page);
            switch (true) {
                case (Interface.search.index.sort=='price' && Interface.search.index.direction=='asc') :
                    $('select[name="sort"]').val("&sort=price&direction=asc");
                    break;

                case (Interface.search.index.sort=='price' && Interface.search.index.direction=='desc') :
                    $('select[name="sort"]').val("&sort=price&direction=desc");
                    break;
            }

            $('select[name="per_page"]').change(function(){
                newLocation = location.toString().replace(/&{0,1}per_page=\d+/g, "");
                newLocation = newLocation.replace(/&{0,1}page=\d+/g, "");
                location = newLocation + '&per_page=' + $(this).val() + '&page=1';
            });

            $('select[name="sort"]').change(function(){
                if ($(this).val() == '0') {
                    return;
                }

                newLocation = location.toString().replace(/&{0,1}sort=[\w|\.{1}]+/g, "");
                newLocation = newLocation.replace(/&{0,1}direction=\w+/g, "");

                // XXX: Very-very quick fix! Refactor for normal logic
                newLocation = newLocation.replace(/per_page/g, "per_rage");
                newLocation = newLocation.replace(/&{0,1}page=\d+/g, "");

                // XXX: Very-very quick fix! Refactor for normal logic
                newLocation = newLocation.replace(/per_rage/g, "per_page");
                location = newLocation + $(this).val() + '&page=1';
            });

            Interface.search.index.loadPointsToMap(0);

            Interface.search.index.button.init();
            Interface.search.index.button.object.click(function(){
                Interface.search.index.loadPointsToMap(Interface.search.maxPointsCount);
                return false;
            });
        },

        loadPointsToMap: function(limit) {
            Interface.search.index.limit = (0 == limit) ? Interface.search.defaultPointsCount : limit;

            // Init map by making ajax request
            Interface.search.index.url = ('' == Interface.search.index.request) ? '/search/map-points/' : '/search/map-points/?';

            // For max count search show modal splash screen
            if (Interface.search.index.limit == Interface.search.maxPointsCount) {
                GeoSplashWindow.show();
            } else {
                Interface.search.index.sendLoadPointsToMapRequest();
            }
        },

        sendLoadPointsToMapRequest: function(callback) {
            var callback = callback || '';
            if(true == Interface.search.index.allPoints) {
                return;
            }
            
            if(0 == Interface.search.index.limit) {
                Interface.search.index.center.zoom = Math.min(5,Interface.search.index.center.zoom);                
                Interface.search.index.initMap('mini-map', []);
                
                Interface.search.index.button.init();
                Interface.search.index.button.show();
                return;
            }
            
            $.getJSON(
                Interface.search.index.url + Interface.search.index.request,
                {limit: Interface.search.index.limit},
                function(data){
                    if( !data || data.errors.length ) {
                        return false;
                    }

                    $.data(document.body, 'points', data.points);

                    Interface.search.index.center.zoom = Math.min(5,Interface.search.index.center.zoom);
                    Interface.search.index.initMap('mini-map',data.points);

                    setTimeout(callback, 50);

                    // Add link on map overlay
                    // Do not show link if we loaded all point set,
                    // or if we try to load max count of points
                    if (Interface.search.index.limit != Interface.search.maxPointsCount
                            && Interface.search.index.limit == data.points.length) {
                        Interface.search.index.button.show();
                    } else {
                        Interface.search.index.allPoints = true;
                        Interface.search.index.button.hide();
                    }

                    return false;
                }
            );
        },

        toggleSearchForm: function() {
            form = $('#inner-search');

            if (form.css('display')=='none') {
                $(form.css('display','block'));
                $('div.close-search-container > a > span').text(Lang._('Close Search'));
            } else {
                $(form.css('display','none'));
                $('div.close-search-container > a > span').text(Lang._('Open Search'));
            }

            return false;
        },

        toggleMap: function(link) {
            Interface.search.index.link = $(link);
            $('#big-map-container, #mini-map').toggle();
            form = $('#inner-search');

            if ($('#big-map-container').css('display')=='none') {
                Interface.search.index.link.find('span').text(Lang._('Show big map'));
                Interface.search.index.initMap('mini-map',$.data(document.body,'points'));

                if (Interface.search.index.bNeedToShowForm) {
                    form.css('display','none');
                    Interface.search.index.toggleSearchForm();
                }

                if(false == Interface.search.index.allPoints) {
                    Interface.search.index.button.object.show();
                }
            } else {
                if(false == Interface.search.index.allPoints) {
                    Interface.search.index.limit = Interface.search.maxPointsCount;
                    GeoSplashWindow.show('Interface.search.index._initBigMap();');
                } else {
                    Interface.search.index._initBigMap();
                }
            }

            return false;
        },

        _initBigMap: function() {
            Interface.search.index.link.find('span').text(Lang._('Hide big map'));

            // If we have open search form - for the first, we have to hide it
            if ('block' == form.css('display')) {
                Interface.search.index.bNeedToShowForm = true;
                Interface.search.index.toggleSearchForm();
            } else {
                Interface.search.index.bNeedToShowForm = false;
            }

            Interface.search.index.button.object.hide();

            Interface.search.index.center.zoom = Math.max(5,Interface.search.index.center.zoom);
            Interface.search.index.initMap('big-map',$.data(document.body,'points'));
        },

        initMap: function(id, points) {
            // For the first - init map
            Geo.initMap(document.getElementById(id), {
                center: Interface.search.index.center,
                icon: {
                    image:		"/img/spot.png",
                    shadow:		"http://www.google.com/mapfiles/shadow50.png",
                    iconsize:		[7, 7],
                    shadowsize:		[0, 0],
                    iconanchor:		[0, 0],
                    infowindowanchor:	[3, 4]
                }
            });

            markers = [];
            Geo.markerOptions = [];
            $.each(points, function(){
                var point = this;
                
                options = {
                    position: Geo.mapApi.getPoint(point.lat,point.lng)
                };

                // If we have to add this marker to cluster, than this location is approximate value
                if(1 == point.cluster) {
                    options.title = Lang._('Approximate location');
                }

                marker = Geo.mapApi.addMarker(options);

                if(1 == point.cluster) {
                    markers.push(marker);
                    Geo.markerOptions.push(point);
                } else {
                    // For markers in cluster we should set other click 
                    google.maps.event.addListener(marker, 'click', function() {
                        if (Geo.mapApi.map.getZoom() > 7) {
                            window.location = "/property/view/"+point.id;
                        }
                    });
                }
            });
            
            // For each marker in list of clustered we should set search facilities
            Geo.clusters = {};
            for(var index in markers) {
                coords = Geo.pointToString(Geo.markerOptions[index].lat, Geo.markerOptions[index].lng);
                Geo.markerOptions[index].coords = coords;
                
                if(!(coords in Geo.clusters)){
                   Geo.clusters[coords] = [];
                } 
                
                Geo.clusters[coords].push(Geo.markerOptions[index].id);                
            }

            for(var index in markers) {
                // For markers in cluster we should set other click 
                google.maps.event.addListener(markers[index], 'click', function() {
                    if (Geo.mapApi.map.getZoom() > 7) {
                        point = this.getPosition();
                        window.location = "/search/?id=" + Geo.clusters[Geo.pointToString(point.lat(), point.lng())].join(',');
                    }
                });
            }

            // Decomment this line if showing cluster is necessary
            Geo.getCluster(markers);

            google.maps.event.addListener(Geo.mapApi.map, 'zoom_changed', function(){
                Geo.mapApi.markersWalk(function(index,marker){
                    current = marker.getIcon();
                    zoom = Geo.mapApi.map.getZoom();

                    if(current.size.height==7 && zoom>=8) {
                        image = new google.maps.MarkerImage(
                            (Geo.pointToString(marker.getPosition().lat(), marker.getPosition().lng()) in Geo.clusters)
                                ? "http://google-maps-icons.googlecode.com/files/villa.png" 
                                : "http://google-maps-icons.googlecode.com/files/home.png",
                            new google.maps.Size(35, 35),
                            new google.maps.Point(0,0),
                            new google.maps.Point(18, 35)
                        );

                        marker.setIcon(image);
                    } else {
                        if(current.size.height!=7 && zoom<=8) {
                            image = new google.maps.MarkerImage(
                                "/img/spot.png",
                                new google.maps.Size(7,7),
                                new google.maps.Point(0,0),
                                new google.maps.Point(3,4)
                            );

                            marker.setIcon(image);
                        }
                    }
                });
            });

            GeoSplashWindow.closeWindow();
        }
    },

    map: {
        request: '',

        init: function() {
            // Init map by making ajax request
            $.getJSON('/search/map-points/?' + Interface.search.map.request, {}, function(data,status){
                if( !data || data.errors.length ) {
                    alert(data.errors.toString());
                    return false;
                }
                // For the first - init map
                Geo.initMap(document.getElementById("mini-map"), {
                    center: Interface.search.index.center,
                    icon: {
                        image:		"/img/spot.png",
                        shadow:		"http://www.google.com/mapfiles/shadow50.png",
                        iconsize:		[7, 7],
                        shadowsize:		[0, 0],
                        iconanchor:		[0, 0],
                        infowindowanchor:	[3, 4]
                    }
                });
                $.each(data.points, function(){
                    Geo.mapApi.addMarker({position: Geo.mapApi.getPoint(this.lat,this.lng)});
                });

                google.maps.event.addListener(Geo.mapApi.map, 'zoom_changed', function(){
                    Geo.mapApi.markersWalk(function(index,marker){
                        current = marker.getIcon();
                        zoom = Geo.mapApi.map.getZoom();

                        if(current.size.height==7 && zoom>8) {
                            image = new google.maps.MarkerImage(
                                "http://google-maps-icons.googlecode.com/files/home.png",
                                new google.maps.Size(35, 35),
                                new google.maps.Point(0,0),
                                new google.maps.Point(18, 35)
                            );

                            marker.setIcon(image);
                        } else {
                            if (current.size.height!=7 && zoom<=8) {
                                image = new google.maps.MarkerImage(
                                    "/img/spot.png",
                                    new google.maps.Size(7,7),
                                    new google.maps.Point(0,0),
                                    new google.maps.Point(3,4)
                                );

                                marker.setIcon(image);
                            }
                        }
                    });
                });
            });
        }
    }
};

