/* This is the story of a Map, a Paginator, and the bakeries that brought them together... */

var cakes = cakes || {};

// Creates a method on jQuery.fn that builds objects.
jQuery.makeBuilder = function (name, fn) {
    jQuery.fn[name] = function (options) {
        return this.map(function () {
            return fn.call(this, options||{});
        });
    }
};

(function TheMap($) {

    var DEFAULTS = {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false
    };

    cakes.Map = function (options) {

        var el           = $(this),
            map          = new google.maps.Map(this, getOptions()),
            data         = null,
            bounds       = null,
            actualBounds = null,
            markers      = [],
            overlay      = null;

        function getOptions() {
            if (options.basic) {
                options.draggable = false;
                options.disableDefaultUI = true;
                options.zoom = 13;
            }
            return $.extend({}, DEFAULTS, options);
        }

        function addMarker(store) {
            var lat     = parseFloat(store.latitude),
                lng     = parseFloat(store.longitude),
                latLng  = new google.maps.LatLng(lat, lng),
                marker  = new cakes.Map.Marker({
                    position: latLng,
                    map:      map,
                    label:    options.basic ? null : $(data.stores).index(store)+1
                });

            if (!options.basic) {
                google.maps.event.addListener(marker, 'click', function () {
                    if (options.tooltips) {
                        addOverlay(store);
                    }
                    el.trigger('storeSelected', store);
                    map.panTo(latLng);
                });
            }

            return marker;
        }

        function addOverlay(store) {
            if (overlay) {
                overlay.setMap(null);
            }

            var lat     = parseFloat(store.latitude),
                lng     = parseFloat(store.longitude);

            overlay = new cakes.Map.Overlay({
                position: new google.maps.LatLng(lat, lng),
                map: map,
                label: $(data.stores).index(store)+1,
                store: store
            });
        }

        function calculateBounds() {
            var minLat, maxLat,
                minLng, maxLng,
                sw, ne,
                listener;

            $.each(data.stores, function () {
                var lat = parseFloat(this.latitude),
                    lng = parseFloat(this.longitude);

                minLat = minLat ? Math.min(minLat, lat) : lat;
                maxLat = maxLat ? Math.max(maxLat, lat) : lat;
                minLng = minLng ? Math.min(minLng, lng) : lng;
                maxLng = maxLng ? Math.max(maxLng, lng) : lng;
            });

            sw = new google.maps.LatLng(minLat,minLng);
            ne = new google.maps.LatLng(maxLat,maxLng);

            if (options.basic) {
                map.panTo(sw);
                map.setZoom(13);
                return;
            }

            bounds = new google.maps.LatLngBounds(sw, ne);
            map.fitBounds(bounds);

            listener = google.maps.event.addListener(map, 'bounds_changed', getActualBounds);

            function getActualBounds() {
                actualBounds = map.getBounds();
                google.maps.event.removeListener(listener);
            }
        }

        function reset() {
            map.setCenter(new google.maps.LatLng(39.30029, -95.88867));
            map.setZoom(4);
            map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
            actualBounds = null;
        }

        reset();

        return {
            setData: function (newData) {
                data = newData;
                if (data.stores.length)
                    calculateBounds();
                else
                    reset();
            },
            showStores: function (startIndex, length) {
                var storesToShow = data.stores.slice(startIndex, startIndex + length);

                $.each(markers, function (marker) {
                    this.setMap(null);
                });
                if (overlay) {
                    overlay.setMap(null);
                    overlay = null;
                }

                if (!options.basic && actualBounds && !actualBounds.equals(map.getBounds())) {
                    map.fitBounds(bounds);
                }

                markers = $.map(storesToShow, addMarker);
            }
        };
    }

    $.makeBuilder('mapify', cakes.Map);

    // Custom Marker with shadow, and text label to show the result number
    cakes.Map.Marker = function (options) {
        this.options = options;

        if (options.map)
            this.setMap(options.map);
    }
    cakes.Map.Marker.prototype = new google.maps.OverlayView();
    $.extend(cakes.Map.Marker.prototype, {
        onAdd: function () {
            var me    = this,
                panes = this.getPanes(),
                div,
                type  = navigator.userAgent.match(/MSIE 6/i) ? '.gif' : '.png';

            this.shadow = $('<div class="map-marker map-shadow">');
            this.marker = $('<div class="map-marker">');

            this.shadow.append('<img src="/images/map_marker-shadow'+type+'">');

            if (this.options.label) {
                this.marker.append('<img src="/images/map_marker'+type+'">');
                this.marker.append('<span class="map-marker-count">'+this.options.label+'</span>');
            } else {
                this.marker.append('<img src="/images/map_marker-star'+type+'">');
            }

            div = this.shadow[0];
            panes.overlayShadow.appendChild(div);

            div = this.marker[0];
            panes.overlayImage.appendChild(div);
            google.maps.event.addDomListener(div, "click", function (event) {
                google.maps.event.trigger(me, "click");
            });
        },
        draw: function () {
            var point = this.getProjection().fromLatLngToDivPixel(this.getPosition()),
                style = {
                    left: point.x + 'px',
                    top: point.y + 'px'
                };

            if (point) {
                this.marker.css(style);
                this.shadow.css(style);
            }
        },
        remove: function () {
            if (this.marker) {
              this.marker.remove();
              this.shadow.remove();
              this.marker = null;
              this.shadow = null;
            }
        },
        getPosition: function () {
            return this.options.position;
        }
    });

    // Custom Overlay to show store details
    cakes.Map.Overlay = function (options) {
        this.options = options;

        if (options.map)
            this.setMap(options.map);
    }
    cakes.Map.Overlay.prototype = new google.maps.OverlayView();
    $.extend(cakes.Map.Overlay.prototype, {
        onAdd: function () {
            var me    = this,
                panes = this.getPanes(),
                li;

            this.overlay = $('<div class="map-overlay">').html('<div class="map-overlay-content">\
                <span class="map-overlay-cap"></span>\
                </div>');

            this.list = $('<ol class="store-list">').html('<li>\
                <a href="#" class="name"></a>\
                <address></address>\
                <span></span>\
                <span></span>\
                <a class="check-link preferred" href="#"><span class="add">Add to</span><span class="remove">Remove from</span> My Bakeries</a>\
                <a class="arrow-link directions" href="#">Get Directions</a>\
                <a class="arrow-link online-ordering" href="#">Online Ordering</a>\
                </li>');

            this.overlay.find('div').append(this.list);
            this.list.attr('start', this.options.label);

            li = this.list.find('li')[0];
            $.data(li, 'view', new cakes.SearchResults.Bakery().init(li).setStore(this.options.store));

            panes.floatPane.appendChild(this.overlay[0]);
        },
        draw: function () {
            var point = this.getProjection().fromLatLngToDivPixel(this.getPosition()),
                style = {
                    left: point.x + 'px',
                    top: point.y + 'px'
                };

            if (point) {
                this.overlay.css(style);
            }
        },
        remove: function () {
            if (this.overlay) {
                this.overlay.remove();
                this.overlay = null;
            }
        },
        getPosition: function () {
            return this.options.position;
        }
    });

})(jQuery);

//

(function ThePaginator($) {

    cakes.Paginator = function (options) {

        var el           = $(this),
            previous     = el.find('a.prev_page').click(showPrevious),
            next         = el.find('a.next_page').click(showNext),
            pageLinks    = el.find('a:not(.next_page, .prev_page)').click(goToPage),

            pageCount    = 0,
            currentPage  = 0,
      startIndex   = 0,
            pagesPerSet  = pageLinks.size(),
            onPageChange = options.onPageChange || function (){};

        function showPrevious() {
          currentPage--;
            update();
            return false;
        }

        function showNext() {
          currentPage++;
            update();
            return false;
        }

        function goToPage() {
            var newPage = startIndex + pageLinks.index(this);

            if (currentPage != newPage) {
                currentPage = newPage;
                update();
            }

            return false;
        }

        function update() {
            onPageChange(currentPage);

            // Hide the paginator outright if we don't have a valid state
          if (!pageCount || !currentPage) {
                el.css('display', 'none');
                return;
            } else {
                el.css('display', '');
            }

            // Update Next link
            next.css('display', currentPage == pageCount ? 'none' : '');

            // Update Previous link
            previous.css('display', currentPage == 1 ? 'none' : '');

            // Update page numbers
      startIndex = Math.max(currentPage - 2, 1);

      // Adjust start index if on next to last page
      if (currentPage == (pageCount -1)) {
        startIndex = Math.max(startIndex - 1, 1);
      }

      // Adjust start index of on last page
      if (currentPage == pageCount) {
        startIndex = Math.max(startIndex - 2, 1);
      }

            for (var i = 0, page, link; i < pagesPerSet; i++) {
                page = startIndex + i;
        link = $(pageLinks[i]);

                link.html(page).css('display', page > pageCount ? 'none' : '');

                if (page == currentPage) {
                    link.addClass('current');
                } else {
                    link.removeClass('current');
                }
            }
        }

        //
        return {
            setPage: function (page) {
                currentPage = page;

                update();
            },

            setPageCount: function (count) {
                pageCount = count;

                // Reset the page to 1 every time we update the number of pages.
                currentPage = 1;
                //currentSet = 1;

                update();
            }
        };
    }

    $.makeBuilder('paginator', cakes.Paginator);

})(jQuery);

//

(function SearchForm($) {

    cakes.SearchForm = function (options) {

        var el       = $(this).submit(search),
            query    = $(this).find('input')[0],
            onSearch = options.onSearch || function (){};

        function search() {
            var url    = el.attr('action'),
                method = el.attr('method'),
                data   = el.serialize();

            function callback(data, textStatus) {
                onSearch(data, query.value);
            }

            $[method](url+'.json', data, callback, 'json');

            return false;
        }

        return this;
    }

    $.makeBuilder('form', cakes.SearchForm);

})(jQuery);

//

(function SearchResults($) {

    cakes.SearchResults = function (options) {

        var el          = $(this),
            listItems   = el.find('li'),
            type        = options.type || cakes.SearchResults.Base,
            stores      = null,
            currentPage = 0;

        // Create the views for each of the list items
        listItems.each(function (index) {
            $.data(this, 'view', new type().init(this));
        });

        // Assign the proper store to each of the views, and update the <ol>'s start.
        function update() {
            if (!stores || !currentPage)
                return;

            var size = listItems.size(),
                startIndex = (currentPage - 1) * size,
                storesToShow = stores.slice(startIndex, startIndex + size),
                i;

            el.attr('start', startIndex + 1);

            for (i=0; i<size; i++) {
                $.data(listItems[i], 'view').setStore(stores[startIndex+i] || null);
            }
        }

        return {
            update: function () {
                update();
            },
            getSize: function () {
                return listItems.size();
            },
            setPage: function (page) {
                currentPage = page;

                update();
            },
            setData: function (data) {
                stores = data.stores;
                currentPage = 1;

                update();
            }
        };
    }

    $.makeBuilder('results', cakes.SearchResults);

    // Search Results Types
    $.extend(cakes.SearchResults, {
        Base: function () {
            this.init = function (element) {
                var el    = this.element = $(element),
                    spans = el.find('span');

                this.preferred = el.find('a.preferred');
                this.onlineOrdering = el.find('a.online-ordering');
                this.storeName = el.find('a.name');
                this.onlineOrder = el.find('.online-ordering');
                this.address   = el.find('address');
                this.phone     = $(spans[0]);
                this.distance  = $(spans[1]);

                var that = this;
                this.preferred.click(function () {
                    that.togglePreferred();
                    return false;
                });

                return this;
            }

            this.setStore = function (store) {
                if (!store) {
                    this.element.hide();
                    return this;
                } else {
                    this.store = store;
                    this.storeName.html(store.name);
                    this.storeName.attr('href', store.relative_url);
                    this.address.html(this.getAddress());
                    this.phone.html(store.phone);
                    if (store.dist)
                      this.distance.html('Distance: ' + parseFloat(store.dist).toFixed(1) + ' Miles');
                    else
                      this.distance.html('');

                    this.element.show();
                }

                this.update();

                return this;
            }

            this.getAddress = function (includeAddress2) {

                var store = this.store,
                    address = store.address1,
                    cityStateZip = store.city + ', ' + store.state + ' ' + store.post_code;

                if (store.address2 && includeAddress2 !== false)
                    address += ' ' + store.address2;

                return address + '<br>' + cityStateZip;
            }

            this.togglePreferred = function () {
                this.store.my_bakery = !this.store.my_bakery;

                $.post('/ajax/preferred_bakeries/', {
                    operation: this.store.my_bakery ? 'create' : 'destroy',
                    bakery_id: this.store.id
                });

                this.element.trigger('toggledPreferred', this.store);
                this.update();
            }

            this.update = function () {
                this.preferred[this.store.my_bakery ? 'removeClass' : 'addClass']('add');
                this.preferred[this.store.my_bakery ? 'addClass' : 'removeClass']('remove');
                this.preferred.attr('title', [this.store.my_bakery ? 'Remove from my Preferred Bakeries' : 'Add to my Preferred Bakeries']);

                this.onlineOrdering.attr('href', this.store.relative_url);
                this.onlineOrdering[this.store.accepts_online_orders ? 'show' : 'hide']();
            }
        },

        Bakery: function () {
            var that     = this,
                init     = this.init;

            this.init = function (element) {
                init.call(this, element);

                // setup links
                this.element.find('a.directions').click(function () {
                    that.googleDirections();
                });

                return this;
            }

            this.googleDirections = function () {
                if (!this.store)
                    return;

                window.location = 'http://maps.google.com/maps?&daddr='+(this.getAddress(false).replace('<br>',' '));
            }
        },

        CakesBakery: function () {
            var that     = this,
                init     = this.init,
                setStore = this.setStore;

            this.init = function (element) {
                init.call(this, element);

                this.input = this.element.find('input').click(showSelect);
                this.storeName.click(showSelect);
                this.onlineOrder.click(showSelect)
                

                // if there isn't a relative url for the online ordering link,
                // then we need the link to behave just like click on the
                // store name and selecting it's corresponding input
                if (this.store && this.store.relative_url == null) {
                  this.onlineOrdering.click(showSelect);  
                }

                function showSelect() {
                    that.input.attr('checked', true);
                    $('#bakerySelection button').show();
                    return $(this).is('input');
                }

                return this;
            }

            this.setStore = function (store) {
                this.input.each(function () {
                    this.checked = false;
                });

                if (store)
                    this.input.attr('value', store.id);
                else
                    this.input.attr('value', '');

                setStore.call(this, store);

                return this;
            }
        }
    });
    var SR = cakes.SearchResults;
    SR.Bakery.prototype = SR.CakesBakery.prototype = new SR.Base();

})(jQuery);

//

(function ThePreferredList($) {

    var HTML = '\
        <a href="#" class="preferred"></a>\
        <a href="#" class="name"></a>\
        <address></address>\
        <span></span>\
        <span class="distance"></span>';

    cakes.PreferredList = function (options) {

        var el   = $(this),
            list = el.find('ul'),
            none = el.find('p');

        function add(store) {
            var li = $('<li>').html(HTML);

            list.append(li);

            li.data('store', store);
            li.data('view', new cakes.SearchResults.Base().init(li).setStore(store));

            list.show();
            none.hide();
        }

        function remove(store) {
            list.find('li').each(function () {
                var li = $(this);
                if (store.id == li.data('store').id) {
                    li.remove();
                }
            });

            if (list.find('li').size() === 0) {
                list.hide();
                none.show();
            }
        }

        function set(stores) {
            $.each(stores, function () {
                add(this);
            });
        }

        return {
            add: add,
            remove: remove,
            set: set
        };
    }

    $.makeBuilder('preferred', cakes.PreferredList);

})(jQuery);

//

(function TheControllers($) {

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\

    The Bakery Search controller

    \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    cakes.BakerySearchController = function (options) {

        var form            = $('#bakerySearch').form({onSearch:searched}),
            resultSummary   = $('#summary-results'),
            resultCount     = $('#summary-results .results'),
            resultQuery     = $('#summary-results .query'),
            maxResultsMet	= $('#summary-results .max-results-met'),
            noresultSummary = $('#summary-noresults'),
            map             = $('.map').mapify({tooltips: true})[0],
            resultList      = $('.store-list').results({type:cakes.SearchResults.Bakery})[0],
            paginator       = $('.pagination').paginator({onPageChange: paged})[0],

            results         = null,
            currentPage     = 0,
            storesPerPage   = resultList.getSize(),
            selectedStore   = null;

        $('.map').bind('storeSelected', storeSelected).bind('toggledPreferred', toggledPreferred);
        $('.store-list').bind('toggledPreferred', toggledPreferred);

        function storeSelected(event, store) {
            selectedStore = store;
        }

        function toggledPreferred(event, store) {
            if (selectedStore) {
                if (selectedStore.id == store.id) {
                    var view = $('.map li').data('view');
                    view.store.my_bakery = store.my_bakery;
                    view.update();
                }

                $.each(results.stores, function () {
                    if (this.id == store.id) {
                        this.my_bakery = store.my_bakery;
                    }
                });
                resultList.setPage(currentPage);
            }
        }

        function searched(data) {
            results = data;
            var pageTracker;

            try {
                pageTracker = _gat._getTracker("UA-8529536-1");
                pageTracker._trackPageview("/bakeries/search");
            } catch(err) {}

            var count = results.stores.length;
            if (count) {
                resultSummary.show();
                noresultSummary.hide();
                resultCount.html(count + ' Results');
                resultQuery.html(results.query);
                if (count == 100) {
                    maxResultsMet.show();
                    maxResultsMet.html('Only the first 100 bakeries are listed.<br/>');
                } else {
                    maxResultsMet.hide();
                }
            } else {
                resultSummary.hide();
                noresultSummary.show();

                if (results.query) {
                    try {
                        pageTracker = _gat._getTracker("UA-8529536-1");
                        pageTracker._trackPageview("/bakeries/search/no-results");
                    } catch(err) {}
                }
            }

            resultList.setData(results);
            map.setData(results);

            paginator.setPageCount(Math.ceil(count / storesPerPage));
        }

        function paged(page) {
            currentPage = page;
            resultList.setPage(page);

            update();
        }

        function update() {
            var startIndex = (currentPage-1) * storesPerPage;
            map.showStores(startIndex, storesPerPage);
        }

        return {
            setResults: searched
        };
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\

    The Cake's Bakery Search controller

    \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    cakes.CakesBakerySearchController = function (options) {

        var form            = $('#bakerySearch').form({onSearch:searched}),
            bakeryPrompt    = $('#bakeryPrompt'),
            bakerySelection = $('#bakerySelection'),
            submitButton    = bakerySelection.find('button'),
            bakeryNoResults = $('#bakeryNoResults'),
            map,
            resultList      = $('.store-list').results({type:cakes.SearchResults.CakesBakery})[0],
            radioList       = $('.store-list input'),
            paginator       = $('.pagination').paginator({onPageChange: paged})[0],

            results         = null,
            currentPage     = 0,
            storesPerPage   = resultList.getSize();

        submitButton.hide();

        function storeSelected(event, store) {
            radioList.each(function () {
                if (this.value == store.id)
                    this.checked = true;
            });

            submitButton.show();
        }

        function searched(data) {
            results = data;
            var pageTracker;

            try {
                pageTracker = _gat._getTracker("UA-8529536-1");
                pageTracker._trackPageview("/order/select-bakery");
            } catch(err) {}

            bakeryPrompt.hide();

            var count = results.stores.length;
            if (count) {
                bakerySelection.show();
                bakeryNoResults.hide();

                // the map needs to be created at this point, because if it's created while the parent element
                // is still none, the map breaks entirely. Sadness.
                if (!map)
                    map = $('.map').bind('storeSelected', storeSelected).mapify()[0];
            } else {
                bakerySelection.hide();
                bakeryNoResults.show();

                if (results.query) {
                    try {
                        pageTracker = _gat._getTracker("UA-8529536-1");
                        pageTracker._trackPageview("/order/select-bakery/no-results");
                    } catch(err) {}
                }
            }

            resultList.setData(results);
            if (map) {
                google.maps.event.trigger(map, 'resize');
                map.setData(results);
            }

            paginator.setPageCount(Math.ceil(count / storesPerPage));
        }

        function paged(page) {
            currentPage = page;
            resultList.setPage(page);

            update();
        }

        function update() {
            var startIndex = (currentPage-1) * storesPerPage;
            if (map)
                map.showStores(startIndex, storesPerPage);
        }

        return {
            setResults: searched
        };
    }


    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\

    The Preferred Bakeries controller

    \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    cakes.PreferredBakeriesController = function (options) {

        var wrapper         = $('#bakeryWrapper').bind('toggledPreferred', toggledPreferred),
            form            = $('#bakerySearch').form({onSearch:searched}),
            bakeryResults   = $('#bakeryResults'),
            bakeryNoResults = $('#bakeryNoResults'),
            preferredList   = $('.bakery-prefs').preferred()[0],
            resultList      = $('.store-list').results({type:cakes.SearchResults.Base})[0],
            paginator       = $('.pagination').paginator({onPageChange: paged})[0],

            map             = null,
            results         = null,
            currentPage     = 0,
            storesPerPage   = resultList.getSize();

        bakeryResults.hide();
        $('.pagination').hide();

        function toggledPreferred(event, store) {
            var pageTracker;

            if (store.my_bakery) {
                preferredList.add(store);

                try {
                    pageTracker = _gat._getTracker("UA-8529536-1");
                    pageTracker._trackPageview("/favorite-this-bakery");
                } catch(err) {}
            } else {
                preferredList.remove(store);

                try {
                    pageTracker = _gat._getTracker("UA-8529536-1");
                    pageTracker._trackPageview("/un-favorite-this-bakery");
                } catch(err) {}
            }

            // Sync up the search data and preferred data
            if (results) {
                $.each(results.stores, function () {
                    if (store.id == this.id) {
                        this.my_bakery = store.my_bakery;
                    }
                });
                resultList.setPage(currentPage);
            }
        }

        function setPreferred(preferred) {
            preferredList.set(preferred);
        }

        function searched(data) {
            results = data;

            var pageTracker;

            try {
                pageTracker = _gat._getTracker("UA-8529536-1");
                pageTracker._trackPageview("/profile/bakeries/search");
            } catch(err) {}

            var count = results.stores.length;
            if (count) {
                bakeryResults.show();
                $('.pagination').show();
                bakeryNoResults.hide();

                // the map needs to be created at this point, because if it's created while the parent element
                // is still hidden, the map breaks entirely. Sadness.
                if (!map)
                    map = $('.map').mapify()[0];
            } else {
                bakeryResults.hide();
                $('.pagination').hide();
                bakeryNoResults.show();

                if (results.query) {
                    try {
                        pageTracker = _gat._getTracker("UA-8529536-1");
                        pageTracker._trackPageview("/profile/bakeries/search/no-results");
                    } catch(err) {}
                }
            }

            resultList.setData(results);
            if (map) {
                google.maps.event.trigger(map, 'resize');
                map.setData(results);
            }

            paginator.setPageCount(Math.ceil(count / storesPerPage));
        }

        function paged(page) {
            currentPage = page;
            resultList.setPage(page);

            update();
        }

        function update() {
            var startIndex = (currentPage-1) * storesPerPage;
            if (map)
                map.showStores(startIndex, storesPerPage);
        }

        return {
            setPreferred: setPreferred,
            setResults: searched
        };
    }

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\

    The Bakery Detail controller (basically a wrapper for the map)

    \* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
    cakes.BakeryDetailController = function (options) {

        var store     = null,
            map       = $('.map').mapify({basic: true})[0],
            preferred = $('.listed-info .preferred').click(togglePreferred);

        function togglePreferred() {
            store.my_bakery = !store.my_bakery;

            $.post('/ajax/preferred_bakeries/', {
                operation: store.my_bakery ? 'create' : 'destroy',
                bakery_id: store.customer_id
            });

            update();
        }

        function update() {
            preferred[store.my_bakery ? 'removeClass' : 'addClass']('add');
            preferred[store.my_bakery ? 'addClass' : 'removeClass']('remove');
            preferred.attr('title', [store.my_bakery ? 'Remove from my Preferred Bakeries' : 'Add to my Preferred Bakeries']);
        }

        return {
            setData: function (data) {
                store = data;

                map.setData({stores:[data]});
                map.showStores(0,1);

                update();
            }
        };
    }

})(jQuery);

