/* Copyright (c) 2008-2009 CloudMade. */
CBSearchSidebar = function (a) {
    this._options = CM.Util.extend({
        resultsNumber: 10,
        container: null
    },
    a || {});
    
    this._options.boundsOnly = false;
    this._id = CM.Util.generateId()
};
CBSearchSidebar.prototype = {
    initialize: function (a) {
        this._map = a;
        
        this._geocoder = new CM.Geocoder(this._options.key)
        
        
        this._markers = [];
        var b = document.createElement('div');
        b.className = 'wml-sidebar-container';
        if (!this._options.container) {
            var c = document.createElement('div');
            c.className = 'wml-sidebar-heading';
            
            //@CB
            //c.innerHTML = 'Search the Map';
            c.innerHTML = localizedStrings['Search the Map'][lang];
            
            b.appendChild(c)
        }
        var d = document.createElement('div');
        d.className = 'wml-sidebar-content';
        b.appendChild(d);
        var f = document.createElement('form');
        f.method = 'get';
        f.className = 'wml-sidebar-input-form';
        f.onsubmit = CM.Util.bind(this._onSubmit, this);
        this._input = document.createElement('input');
        this._input.type = 'text';
        this._input.className = 'wml-sidebar-input';
        f.appendChild(this._input);
        
        /* @CB
        if (!this._options.container) {
            CM.Event.addListener(this._map, 'sidebaropened', this._onSidebarOpened, this);
            CM.Event.addListener(this._map, 'sidebarclosed', this._onSidebarClosed, this)
        }*/
        var g = document.createElement('input');
        g.type = 'image';
        g.className = 'wml-sidebar-go';
        g.src = CM.Util.getRootUrl() + 'images/search/go.png';
        f.appendChild(g);
        d.appendChild(f);
        this._list = document.createElement('div');
        this._list.className = 'wml-search-panel-list';
        d.appendChild(this._list);
        this._pager = document.createElement('div');
        this._pager.className = 'wml-search-panel-pager';
        d.appendChild(this._pager);
        /*@CB
        if (!this._options.container) {
            var h = document.createElement('a');
            h.href = '#close-sidebar';
            h.className = 'wml-sidebar-close';
            h.onclick = CM.Util.bind(this._onCloseClick, this);
            b.appendChild(h)
        }
        if (!this._options.container) {
            this._map.setSidebarContent(b, 215)
        } else {
            this._options.container.appendChild(b)
        }*/
        
        //@CB
        this._map.setSidebarContent(b, 215)
        
    },
    /*@CB
    _onCloseClick: function () {
        this._map.closeSidebar();
        return false
    },
    _onSidebarOpened: function () {
        this._input.focus()
    },
    _onSidebarClosed: function () {
        this._input.value = '';
        this._clearResults()
    },*/
    _onSubmit: function (a) {
        var b = (typeof a == 'number');
        if (!b) {
            CM.Event.fire(this, 'search', this._input.value)
        }
        this._activePage = (b ? a : 0);
        this._query = (b ? this._query : this._input.value);
        if (!this._query) {
            return false
        }
        if (b) {
            this._map.zoomToBounds(this._bounds)
        } else {
            this._bounds = this._map.getBounds()
        }
        this._clearResults();
        //@CB
        //this._list.innerHTML = '<div class="wml-search-panel-item">Searching the map...</div>';
        this._list.innerHTML = '<div class="wml-search-panel-item">' + localizedStrings['Searching the map...'][lang]  + '</div>';
        this._geocoder.getLocations(this._query, CM.Util.bind(this._handleResponse, this), {
        	//@CB
            //bounds: this._bounds,
            boundsOnly: this._options.boundsOnly,
            activePage: this._activePage,
            detailedDescription: true,
            resultsNumber: this._options.resultsNumber
        });
        return false
    },
    _clearResults: function () {
        this._map.closeInfoWindow();
        for (var a = 0; a < this._markers.length; a++) {
            this._map.removeOverlay(this._markers[a])
        }
        this._markers = [];
        this._list.innerHTML = '';
        this._pager.innerHTML = ''
    },
    _handleResponse: function (c) {
        var d = c.features || c.points;
        if (!d || (d && !d.length)) {
        	//@CB
            //this._list.innerHTML = '<div class="wml-search-panel-item">No results found.</div>';
        	this._list.innerHTML = '<div class="wml-search-panel-item">' + localizedStrings['No results found.'][lang] + '</div>';
            return
        }
        
        /**
         * if there is only one result, zoom and show guide -> true
         * otherwise just draw the results, but no guides -> false
         */
        //@CB
        if(d.length > 1) {
	        this._list.innerHTML = '';
	        for (var f = 0; f < d.length; f++) {
	            var g = '';
	            var h = ((this._activePage * this._options.resultsNumber) + f + 1) + '';
	            for (var j = 0, l = (d.length + '').length - h.length; j < l; j++) {
	                g += '0'
	            }
	            h = g + h;
	            this._processGeocodingPoint(d[f], h, false);
	        }
        }
        //@CB
        else if (d.length == 1){
        	this._list.innerHTML = '';
	        for (var f = 0; f < d.length; f++) {
	            var g = '';
	            var h = ((this._activePage * this._options.resultsNumber) + f + 1) + '';
	            for (var j = 0, l = (d.length + '').length - h.length; j < l; j++) {
	                g += '0'
	            }
	            h = g + h;
	            this._processGeocodingPoint(d[f], h, true);
	        }
        }
        
        
        var k = c.found ? Math.ceil(c.found / this._options.resultsNumber) : c.points[0].pageCount;
        if (k > 1) {
            for (f = 0; f < Math.min(k, this._options.resultsNumber); f++) {
                (function (a) {
                    var b = document.createElement('a');
                    b.className = 'wml-search-panel-page-num';
                    if (a == this._activePage) {
                        b.className += '-selected'
                    }
                    b.href = '#search-result-page-' + (a + 1);
                    b.onclick = CM.Util.bind(function () {
                        this._onSubmit(a);
                        return false
                    },
                    this);
                    b.innerHTML = a + 1;
                    this._pager.appendChild(b)
                }).call(this, f)
            }
        }
    },
    _processGeocodingPoint: function (a, b, center) {
    	
    	//make markers
        var c = a.centroid.coordinates,
            d = new CM.LatLng(c[0], c[1]);
        
        var f = (a.properties && (a.properties.name || a.properties.synthesized_name)) || "(untitled)";
        
        var g = new CM.LabeledMarker(d, {
            title: b
        });
        
        //@CB
        var sw = new CM.LatLng(a.bounds[0][0], a.bounds[0][1]);
        var ne = new CM.LatLng(a.bounds[1][0], a.bounds[1][1]);
        var bounds = new CM.LatLngBounds(sw, ne);
        //g.bindInfoWindow('<a href="" onClick="alert(asdasd);"' + f + '</a>', {}, CM.DataCard);
        //g.bindInfoWindow(f + ' ' + f, {}, CM.DataCard);
        //g.bindInfoWindow('<span onclick="alert(2);">KLICK</span>', {}, CM.DataCard);
        CM.Event.addListener(g, 'click', function() {
        	
        	//map.zoomToBounds(bounds);
        	map.setCenter(d);
        	
        	//map.setCenter(d, 11);
        	g.openInfoWindow('<b>' + f + '</b>', {}, CM.DataCard);
        	getAndDrawLocation(c[0], c[1]);        	
		});
        
        map.addOverlay(g);
        this._markers.push(g);
        
        f = f.replace(new RegExp(this._query, "gi"), '<b>' + this._input.value + '</b>');
        var h = document.createElement('a');
        h.className = 'wml-search-panel-item';
        h.href = '#search-result-' + b;
        h.onclick = function () {
            CM.Event.fire(g, 'click');
            return false
        };
        h.innerHTML = '<span class="wml-search-panel-item-num">' + b + '</span> ' + f;
        this._list.appendChild(h)
        
        //@CB
        if(center) {
        	
        	//map.zoomToBounds(bounds);
        	map.setCenter(d);
        	//map.setCenter(d, 11);
        	g.openInfoWindow('<b>' + f + '</b>', {}, CM.DataCard);
        	getAndDrawLocation(c[0], c[1]);
        }
    }
};
