/* */

function SearchNearestControl(btn_submit_name) {
    
    var last_where = '';
    var last_what = '';
    var last_token = '';
    var results_page = 1;
    var hide_categories_above = 5;
    var hide_categories_if_total = 7;
    var show_filter_flag = false;
    var results_in_category = '';
    var search_results_cache = [];
    var location;
    var selected_item_id = '';
    var that = this;
    var is_panel_visible = true;
    var _map_marked_pois = [];
    var _optimal_bbox = undefined;

    var _companies_list_visible;

    var _results_found=false;

    var search_location = new Location();
    var alt_address_control = new AddressControl(search_location,
                                                 'search_nearest_where',
                                                 'search_nearest_alt_addresses_box',
                                                 'search_nearest_alt_addresses',
                                                 'search_nearest_alt_addresses_arrow_img',
                                                 'search_nearest_alt_addresses_arrow');

    function onMapCenter() {
        if (_optimal_bbox) {
            mvfa.fit_bbox(_optimal_bbox.left,_optimal_bbox.top,_optimal_bbox.right,_optimal_bbox.bottom,0.8);
        }
    }

    function setPanelVisible(param) {
        is_panel_visible = (param != false);
        if (param==false) {
            makeInvisible('results_box_header');
            makeInvisible('results_box');
            makeInvisible('results_box_footer');
        }
        else {
            makeVisible('results_box_header');
            makeVisible('results_box');
            makeVisible('results_box_footer');
            makeVisible('search_form');
            mvfa.pois_enable('poi-s',true);
            mvfa.pois_enable('poi-1',true);
            mvfa.pois_enable('poi-b',true);
            mvfa.pois_clear("poi-s");
            mvfa.pois_set("poi-s",_map_marked_pois);
            mvfa.pois_clear("poi-r");
            mvfa.pois_set('poi-r',that.getBaseLocationPOI());
            SetMenuState(menu_search,true);
            eventMapper.setListener('mv-pois.map-center-action',onMapCenter);
            linkHereDB.switchToken(true);
        }
    }

    this.setPanelVisible = setPanelVisible;

    this.getMarkedPOIs = function () { return _map_marked_pois; }

    this.getBaseLocationPOI = function () { return [search_location.serializeSWF("search-nearest-center",-2)]}

    this.isPanelVisible = function() { return is_panel_visible; }

    this.isCompaniesListVisible = function() { return _companies_list_visible; }

    this.getSearchLocation = function(){ return search_location; }

    function getLastAddress() {
        return last_where;
    }

    this.getLastAddress = getLastAddress;

    function getLastSearchPhrase() {
        return last_what;
    }
    
    function getResultsCategory() {
        return results_in_category;
    }
    this.getResultsCategory = getResultsCategory;

    this.getLastSearchPhrase = getLastSearchPhrase;

    function onNearestResponseFail(response) {
        setMessage("Przepraszamy, błąd połączenia z serwerem. Spróbuj ponownie.",msg_delay);
        $('status_messages').style.color= '#0000ff';
    }
    this.onNearestResponseFail = onNearestResponseFail;
    function onSubmitNearestNewSearch(ev) {
        clearMessage();
        clearVCardData(false);
        makeInvisible('search_nearest_results_box_header');
        makeInvisible('vcard_box');
        $('search_results_list_box').innerHTML = '';
        $('search_filter_list_box').innerHTML = '';
        show_filter_flag = false;
        makeNearestRequest(true,true,true,0,true);
        return false;
    }

    function onCategorySelected(category_id, category_item, bbNo) {
        results_page = 1;
        makeNearestRequest(true,true,false,category_id, false, bbNo);
        boldSelectedItem(category_item);
        //    $('filter_search_results_switch').innerHTML = 'Wróć';
    }
    
    function onSearchInSelected(searchInName,searchInOffer,showCategories,category_id,new_search,lastBBNo, item_id) {
        results_page = 1;
        makeNearestRequest(searchInName,searchInOffer,showCategories,category_id,new_search,lastBBNo);
        boldSelectedItem(item_id);

    }

    function boldSelectedItem(item_id) {
        if (selected_item_id != '') {
            $(selected_item_id).removeAttribute('class');
      $(selected_item_id).className = '';
        }
        selected_item_id = item_id;
        $(selected_item_id).className = 'search_nearest_selected_item';
        // Zmiana nazwy switcha zawezania + podmiana strzalki
        $('filter_search_results_switch').innerHTML = 'Filtracja wyników';
        $('filter_search_results_img').src = '_gfx/arr_roll_down.gif';
    }

    
//    function boldSelectedCategorie(category_no) {
//        if (selected_categorie_id != '') {
//            $('search_nearest_select_cat_'+selected_categorie_id).removeAttribute('class');
//        }
//        selected_categorie_id = category_no;
//        $('search_nearest_select_cat_'+selected_categorie_id).className = 'search_nearest_selected_item';
//    }

    function updateLocation(address_data) {
        search_location.update(address_data);
        $("search_nearest_where").value = search_location.getAddressFull();
        mvfa.pois_clear('poi-r');
        mvfa.pois_set('poi-r',that.getBaseLocationPOI());
        mvfa.pois_enable('poi-r',true);
    }
    this.updateLocation = updateLocation;

    function _updatePagesFooter(curr_page,last_page) {
        if (last_page!=undefined)
            that.last_page = last_page;
        else {
            last_page = that.last_page;
        }
        
        if (last_page>1) {
            
            pnblock = '<div id="pager">';
            pnblock += '<div class="right">';
            pnblock += '<a href="#" id="search_results_page_next"><img src="_gfx/button_right.png" alt="" title="" border="0" /></a>';
            pnblock += '</div>';
            pnblock += '<div class="left">';
            pnblock += '<a href="#" id="search_results_page_prev"><img src="_gfx/button_left.png" alt="" title="" border="0" /></a>';
            pnblock += '</div>';
      
            var startpage = Math.max(1,Math.min(curr_page-5,last_page-11));
            var stoppage = Math.min(Math.max(curr_page+5,11),last_page);
            
            for (var page=startpage; page <= stoppage; page++) {
                if (page == curr_page) {
                    pnblock += "<strong>"+page+"</strong> ";
                }
                else {
                    pnblock += "<a id=\"search_results_page_"+page+"\" href=\"#\">"+page+"</a> ";
                }
            }
            pnblock += '</div>';
            $('results_box_footer').innerHTML = pnblock;
            
            for (var page=startpage; page <= stoppage; page++) {
                if (page != curr_page) {
                    $('search_results_page_'+page).onclick = partial(_switchToPage,page);
                }
            }
            
            $('search_results_page_next').onclick = partial(_switchToPage,Math.min(last_page,curr_page+1));
            $('search_results_page_prev').onclick = partial(_switchToPage,Math.max(1,curr_page-1));
      
      if (curr_page == 1) {
        makeInvisible('search_results_page_prev');
      }
      
      if (curr_page == last_page) {
        makeInvisible('search_results_page_next');
      }
        }
        else {
            $('results_box_footer').innerHTML = '';
        }
    }
    
    function makeNearestRequest(searchInName,searchInOffer,showCategories,category_id,new_search,lastBBNo) {

        var request;

        _companies_list_visible = false;
        _map_marked_pois = [];

        if (searchInName==undefined) {
            searchInName = that.last_searchInName;
            searchInOffer = that.last_searchInOffer;
            showCategories = that.last_showCategories;
            category_id = that.last_category_id;
        }
        else {
            that.last_searchInName = searchInName;
            that.last_searchInOffer = searchInOffer;
            that.last_showCategories = showCategories;
            that.last_category_id = category_id;
            that.search_results_cache = [];
            $('results_box_footer').innerHTML = '';
            that.results_page = 1;
        }
        makeInvisible('search_nearest_alt_addresses_box');
        makeInvisible('search_nearest_alt_addresses_arrow');
        mvfa.pois_clear("poi-s");

        request = {method: "SearchNearest",
                   searchInName: searchInName,
                   searchInOffer: searchInOffer,
                   showCategories : showCategories
        };
        if (new_search==true) {
            last_where = $("search_nearest_where").value;
            last_what = $("search_nearest_what").value;
            }
        request.where = last_where;
        request.what = last_what;
        request.results_page = that.results_page;

        if (category_id>0) {
            request['category'] = category_id;
        }

        if (search_location.getAddressFull() == $("search_nearest_where").value) {
            request.selected_address = serializeJSON(search_location.serialize());
        }

        request.resultsBBNo = lastBBNo;

        _def = loadJSONDoc(JSON_REQUESTS_PATH,
                           request);
        makeInvisible('advert_box');
        setMessage("Proszę czekać.");
        $('status_messages').style.color= '#0000ff';
        _def.addCallbacks(onNearestResponse,onNearestResponseFail);
        return false;
    }

    function onSwitchFilter() {
	/*
        if (isVisible('search_filter_list_box')) {
            makeVisible('search_results_list_box');
            makeInvisible('search_filter_list_box');
            makeVisible('status_messages');
            makeVisible('status_msg_border');
            $('filter_search_results_switch').innerHTML = 'Zawęź';
            $('filter_search_results_img').src = '_gfx/arr_roll_down.gif';
        }
        else {
            makeInvisible('search_results_list_box');
            makeVisible('search_filter_list_box');
            makeInvisible('route_status_msg_border');
            makeInvisible('route_status_messages');
            makeInvisible('status_messages');
            makeInvisible('status_msg_border');
            $('filter_search_results_switch').innerHTML = 'Wróć';
            $('filter_search_results_img').src = '_gfx/arr_roll_up.gif';
        }
	*/

	if (isVisible('search_filter_list_box')) {
            //makeVisible('search_results_list_box');
            makeInvisible('search_filter_list_box');
            makeVisible('status_messages');
            makeVisible('status_msg_border');
            $('filter_search_results_switch').innerHTML = 'Filtracja wyników';
            $('filter_search_results_img').src = '_gfx/arr_roll_down.gif';
        }
        else {
            //makeInvisible('search_results_list_box');
            makeVisible('search_filter_list_box');
            makeInvisible('route_status_msg_border');
            makeInvisible('route_status_messages');
            makeInvisible('status_messages');
            makeInvisible('status_msg_border');
            $('filter_search_results_switch').innerHTML = 'Filtracja wyników';
            $('filter_search_results_img').src = '_gfx/arr_roll_up.gif';
        }
    }

    function _switchToPage(pageno) {
        if (that.search_results_cache[pageno] != undefined) {
            _showResultsPage(pageno);
            _updatePagesFooter(pageno);
        }
        else {
            that.results_page = pageno;
            $('search_results_list_box').innerHTML = '';
            makeNearestRequest();
        }
        return false;
    }

    function showMoreCategories() {
        makeInvisible('search_nearest_select_cat_show_more');
        makeVisible('search_nearest_select_cat_more');
    }

    function hideMoreCategories() {
        makeVisible('search_nearest_select_cat_show_more');
        makeInvisible('search_nearest_select_cat_more');
    }
    
    function _showResultsPage(page) {
        _companies_list_visible = true;
        if (that.search_results_cache[page]!=undefined) {
            makeInvisible('advert_box');
            $('filter_search_results_switch').innerHTML = 'Filtracja wyników';
            $('filter_search_results_img').src = '_gfx/arr_roll_down.gif';
            var data = that.search_results_cache[page];
            $('search_results_list_box').innerHTML = data['html'];
            for (company_id in data['companies']) {
                $('companybox_'+data['companies'][company_id]['temporaryId']).onclick = 
                    partial(function (x,y,z) {
                        //mvfa.set_coords(x,y,mvfa.get_scale());
                        mvfa.simulate_poi_mouse_click_and_set_coords('poi-s',z, x, y, mvfa.get_scale() );
                    },data['companies'][company_id]['x92'],data['companies'][company_id]['y92'],data['companies'][company_id]['temporaryId']);
                $('companybox_'+data['companies'][company_id]['temporaryId']).onmouseover = partial(onMouseOverSearchResult,data['companies'][company_id]['temporaryId']);
                $('companybox_'+data['companies'][company_id]['temporaryId']).onmouseout = partial(onMouseOutSearchResult,data['companies'][company_id]['temporaryId']);
                
                var route_target = new Location;
                route_target.update(
                    {x92: data['companies'][company_id]['x92'],
                     y92: data['companies'][company_id]['y92'],
                     address_full: data['companies'][company_id]['address_full'],
                     address_struct: {"province": data['companies'][company_id]['voivodeship'],
                                      "region": data['companies'][company_id]['region'],
                                      "commune": data['companies'][company_id]['commune'],
                                      "city": data['companies'][company_id]['city'],
                                      "street": data['companies'][company_id]['street'],
                                      "houseno": data['companies'][company_id]['streetNo']}});
                $('company_route_to_'+data['companies'][company_id]['temporaryId']).onclick = partial(trace_route.routeToPointAction,route_target);

            }
            mvfa.blockpoppoi(999);
            mvfa.pois_set("poi-s",data['mapdata']);
            _map_marked_pois = data['mapdata'];
            _optimal_bbox = data.bbox;
            if (linkHereDB.getLinkStep() == 0) {
                mvfa.fit_bbox(data.bbox.left, data.bbox.top, data.bbox.right, data.bbox.bottom, 0.8);
             }
        }
    }

    var search_result_hide_delayed = undefined;

    function onMouseOverSearchResult(x) {
        skip_mvf_change = false;
        if (search_result_hide_delayed != undefined) {
            if (search_result_hide_delayed[0] == x) {
                skip_mvf_change = true;
            }
            else {
                mvfa.simulate_poi_mouse_out('poi-s',search_result_hide_delayed[0]);
            }
            clearTimeout(search_result_hide_delayed[1]);
        }
        is_mouse_over_simulated = true;
        if (!skip_mvf_change) {
            mvfa.simulate_poi_mouse_over('poi-s',x);
        }
        addElementClass('companybox_'+x,'wynik_styl_1');
        removeElementClass('companybox_'+x,'wynik_styl_2');

    }
    
   function onMouseOutSearchResult(x) {
        is_mouse_over_simulated = false;
        search_result_hide_delayed = [x,setTimeout( function() {
                    mvfa.simulate_poi_mouse_out('poi-s',x);
                    search_result_hide_delayed = undefined;
          }, 100)];
        removeElementClass('companybox_'+x,'wynik_styl_1');
        addElementClass('companybox_'+x,'wynik_styl_2');

    }


    function areResultsFound() {
        return _results_found;
    }
    this.areResultsFound = areResultsFound;
    
    function onNearestResponseFromLink(response){
        that.search_results_cache = [];
        _companies_list_visible = false;
        _map_marked_pois = [];
        $('results_box_footer').innerHTML = '';
        last_what = $("search_nearest_what").value = response['what_phrase'];
        last_where = $("search_nearest_where").value = response['addresses'][0]['address_full'];
        that.last_searchInName = response['requested']['searchInName'];
        that.last_searchInOffer = response['requested']['searchInOffer'];
        that.last_showCategories = response['requested']['showCategories'];
        that.last_category_id = response['requested']['category'];
        onNearestResponse(response);
        linkHereDB.performStep(); 
    }
    this.onNearestResponseFromLink = onNearestResponseFromLink;
    function onNearestResponse(response) {
        clearMessage();
        
        _optimal_bbox = undefined;

        if (response.warning) {
            setMessage(response.warning,msg_delay);
            $('status_messages').style.color= '#0000ff';
            return;
        }
        linkHereDB.last_nearest_token = response['link_token'];
        if (response.mapsearch.resultsCount==0 || response.mapsearch.resultsCount == undefined || response.mapsearch.resultsCount == "") {
            mvfa.pois_clear("poi-s");
            if ($('search_nearest_where').value.length != 0) {
                if (response.addresses_cnt==0) {
                    setMessage("Nie znaleziono podanej lokalizacji.",msg_delay);
                    $('status_messages').style.color= '#0000ff';
                }
                else if ($('search_nearest_what').value.length != 0) {
                    setMessage("Nie znaleziono wyników spełniających kryteria wyszukiwania.",msg_delay);
                    $('status_messages').style.color= '#0000ff';
                }
            }
            _results_found = false;
        }
        else {
            clearMessage();
            
            _results_found = false;

            linkHereDB.updatelink(response['link_token']);

            var cblock='', fblock='', pnblock='';
            
            if (response['mapsearch']['keywords']!=undefined) {
                var searchWord = ''
    				searchWord = response['mapsearch']['keywords']['base']['_cdata'];
    				if((response['mapsearch']['keywords']['base']['_attrs']['found']=="n") && (response['mapsearch']['keywords']['correct']['_attrs']['found']=="y")){
    					if((response['mapsearch']['keywords']['correct']['_attrs']['corrected']!=undefined) && (response['mapsearch']['keywords']['correct']['_attrs']['corrected']!="")){
    						$("search_nearest_what").value  = response['mapsearch']['keywords']['correct']['_attrs']['corrected'];
    						searchWord = response['mapsearch']['keywords']['correct']['_attrs']['corrected'];
    					}else if((response['mapsearch']['keywords']['correct']['_cdata']!=undefined) && (response['mapsearch']['keywords']['correct']['_cdata']!="")){
    						$("search_nearest_what").value  = response['mapsearch']['keywords']['correct']['_cdata'];
    						searchWord = response['mapsearch']['keywords']['correct']['_attrs']['corrected'];
    					}
    				}
            }

            if (response['mapsearch']['companies'] != undefined) {
                _results_found = true;
                
                var companies = response['mapsearch']['companies']['company'];
                
                if (response['requested']['category']>0) {
                    cblock += '<h1>Branża <strong>'+response['mapsearch']['categoryName']+' ('+response['mapsearch']['resultsCount']+')</strong></h1>\n';
                    results_in_category = response['mapsearch']['categoryName'];
                }
                else if ((response['mapsearch']['categories'] != undefined)
                         && (response['mapsearch']['categories']['category'].length == 1)
                         && (response.requested.searchInName=="true")
                         && (response.requested.searchInOffer=="true")
                         && (response.requested.showCategories=="true")
                        ) {
                    cblock += '<h1>Branża <strong>'+response['mapsearch']['categories']['category'][0]['name']+' ('+response['mapsearch']['resultsCount']+')</strong></h1>\n';
                    results_in_category = response['mapsearch']['categories']['category'][0]['name'];
                }
                else if ((response['mapsearch']['keywords']['original']!="") &&
                         (response['mapsearch']['keywords']['base']['_cdata']!="")) {
                    
						var searchWord = ''
						searchWord = response['mapsearch']['keywords']['original'];
        				
						if(response['mapsearch']['keywords']['base']['_attrs']['found']=="n") {
							if(response['mapsearch']['keywords']['correct']['_attrs']['found']=="y") {
								if((response['mapsearch']['keywords']['correct']['_attrs']['corrected']!=undefined) && (response['mapsearch']['keywords']['correct']['_attrs']['corrected']!="")){
									$("search_nearest_what").value  = response['mapsearch']['keywords']['correct']['_attrs']['corrected'];
									searchWord = response['mapsearch']['keywords']['correct']['_attrs']['corrected'];
								} else if((response['mapsearch']['keywords']['correct']['_cdata']!=undefined) && (response['mapsearch']['keywords']['correct']['_cdata']!="")){
									$("search_nearest_what").value  = response['mapsearch']['keywords']['correct']['_cdata'];
									searchWord = response['mapsearch']['keywords']['correct']['_cdata'];
								}
						}
					}
                    
                    cblock += '<h1>Szukana fraza: <strong>'+
                        searchWord+' ('+response['mapsearch']['resultsCount']+')</strong></h1>\n';
                    results_in_category = '';
                }
                cblock += '<div class="r_list">\n';
                var iteration = 0;
                for (company_id in companies) {
                    if(iteration==0){
                        cblock += '<div id="companybox_'+companies[company_id]['temporaryId']+'" class="companybox wynik_styl_2 first_elem';
                    }else{
                        cblock += '<div id="companybox_'+companies[company_id]['temporaryId']+'" class="companybox wynik_styl_2';
                    }
                    if (iteration==companies.length-1) {
                        cblock += " wynik_styl_last";
                    }
                    cblock += '">\n';
                    var isGolden =false;//TODO:tu zmienic na false przed wrzutem
                    if(companies[company_id]['goldenLinkUrl']!="" && companies[company_id]['goldenLinkUrl']!=undefined ){
                        isGolden = true;
                    }
                    cblock += '<div class="wynik_header left'+(isGolden?'_goldenlink':'')+'">\n';
                    
                    if (isIE6() == false) {
                        cblock += '<div class="r_list_left_number"><img src="_gfx/geo3/g'+(iteration+1)+'.png" border="0" alt="" style="padding-bottom: 6px;" /></div>\n';
                    }
                    else {
                       cblock +='<div class="r_list_left_number"><div style="width:30px; height:30px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'_gfx/geo3/g'+(iteration+1)+'.png\', sizingMethod=\'scale\')"></div></div>\n';
                       cblock +='<br style="clear:both;"/>\n'

                        //cblock +='<div class="r_list_left_number"><img style="width:25px; height:25px; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'_gfx/geo3/g'+(iteration+1)+'.png\', sizingMethod=\'scale\')"/></div>\n';
                    }
		    cblock += '</div>\n';
		    cblock += '<div class="search_res_content_box">'
                    cblock += '<div><div class="h3"><a href="#" id="company_name_'+companies[company_id]['temporaryId']+'">'+companies[company_id]['companyName']+'</a><span style="text-decoration: none; color: #707070; font-weight: normal; font-size:10px;">&nbsp;&ndash; '+companies[company_id]['distance']+'&nbsp;km</span></div>\n';
                    //cblock += '<div class="clear"></div></div></div>';
                    //cblock += '<div class="wynik_inner">';
                    if (results_in_category == '') {
                        cblock += '<p class="results-branch">Branża: <a href="http://www.pf.pl/serwis/'+companies[company_id]['categoryName'].replace(/[ ,\.\"\'-]+/gi,"+")+'-B'+companies[company_id]['categoryId']+'V3_YP.html" target="_blank">'+companies[company_id]['categoryName']+'</a></p>';
                    }
                    cblock += '<p class="company_info">'+companies[company_id]['idltw']+'</p>\n';
                    cblock += '<p>'+companies[company_id]['address_full']+'</p>\n';
                    if (companies[company_id]['phone'].length>0) {
                        cblock += '<span style="margin-left:5px">tel. <a href="callto:'+companies[company_id]['phone']+'">'+companies[company_id]['phone']+'</a></span>\n';
                    }
		    if (companies[company_id]['hasInfoPage']=='true') {
                        cblock += '<span style="margin-left:5px"><a href="http://www.pf.pl/serwis/'+companies[company_id]['parsedName']+'-C'+companies[company_id]['companyId']+'B'+companies[company_id]['categoryId']+'_INF.html" target="_blank" >Wizytówka</a></span>\n';
                    } 
                    if (companies[company_id]['www'].length>0) {
                        cblock += '<p style="display:none;"><a target="_new" href="'+companies[company_id]['www']+'">'+companies[company_id]['www'].substring(7)+'</a></p>\n';
                    }
                    cblock += '<ul class="results-options-2" style="display:none;">\n';
                    if (companies[company_id]['hasInfoPage']=='true') {
                        cblock += '<li><a href="http://www.pf.pl/serwis/'+companies[company_id]['parsedName']+'-C'+companies[company_id]['companyId']+'B'+companies[company_id]['categoryId']+'_INF.html" target="_blank" ><img src="_gfx/ico_wizyt.gif" border="0" alt="Wizytówka" title="Wizytówka"/></a></li>\n';
                    }
                    if (companies[company_id]['hasMap']=='true') {
                        cblock += '<li><a href="'+companies[company_id]['parsedName']+'-C'+companies[company_id]['companyId']+'B'+companies[company_id]['categoryId']+'_MAP.html"><img src="_gfx/ico_mapa.gif" border="0" alt="Mapa" title="Mapa"/></a></li>\n';
                    }
                    cblock += '<li><a href="#" id="company_route_to_'+companies[company_id]['temporaryId']+'" ><img src="_gfx/ico_car.gif" border="0" alt="" title="Dojazd"/></a></li>\n';
                    if (companies[company_id]['e_mail'].length>0) {
                        cblock += '<li><a href="http://www.pf.pl/serwis/'+companies[company_id]['parsedName']+'-C'+companies[company_id]['companyId']+'B'+companies[company_id]['categoryId']+'_wyslij-email-do-firmy.html" target="_blank"><img src="_gfx/ico_email.gif" border="0" alt="E-mail" title="E-mail" /></a></li>\n';
                    }
                    if (companies[company_id]['namedLinkText']=='Rezerwuj'){
                        cblock += '<li><a href="'+companies[company_id]['namedLinkUrl']+'" target="_blank"><img src="_gfx/ico_rez.gif" border="0" alt="Rezerwacja"  title="Rezerwacja"/></a></li>\n';
                    }
                    cblock += '</ul>\n';
		    
		    cblock += '</div></div>\n'; //do prawego diva
		    cblock += '<br style="clear:both;"/>\n';
		    cblock += '</div>\n';//do calego kontenera dla wyniku
                    iteration++;
                }
		
                cblock += '<div class="wynik_bottom"><div class="wynik_bottom_inner"></div></div>';
                cblock += '</div>\n';


                var last_page = 1+Math.floor((response.mapsearch.resultsCount-1)/response.resultsPerPage);
                _updatePagesFooter(response.resultsPageNumber,last_page);

                that.search_results_cache[response.resultsPageNumber] = {
                    'html':cblock,
                    'mapdata': response.mapdata,
                    'companies': companies,
                    'bbox': response.bbox
                };

                var msg_search = "Wynik wyszukiwania w promieniu ";
                if (response.mapsearch.resultsBoundingBoxNumber == undefined ||
                    response.mapsearch.resultsBoundingBoxNumber == "") {
                    msg_search += response.mapsearch.dists[0];
                }
                else {
                    msg_search += response.mapsearch.dists[response.mapsearch.resultsBoundingBoxNumber];
                }
                msg_search += " km od ";
                
                if (response.addresses[0].address_struct.level=="city") {
                    msg_search += "centrum miasta.";
                    setMessage(msg_search, msg_delay);
                    $('status_messages').style.color= '#666666';
                }
                else if (response.addresses[0].address_struct.level == "street" ||
                         response.addresses[0].address_struct.level == "addresspoint") {
                    msg_search += "podanej lokalizacji.";
                    setMessage(msg_search, msg_delay);
                    $('status_messages').style.color= '#666666';
                }
                    
                _showResultsPage(response.resultsPageNumber);
            }
            var show_categories = false;

            if (($('search_filter_list_box').innerHTML == ''&&linkHereDB.getLinkStep()==0)
                ||($('search_filter_list_box').innerHTML == '' && linkHereDB.getLinkStep()!=0 && response['mapsearch']['categories'] != undefined)
              ) { 
                
                fblock += '<div class="r_list" class="clearstyle">\n';
                var searchWord = ''
                    searchWord = response['mapsearch']['keywords']['base']['_cdata'];
					if((response['mapsearch']['keywords']['base']['_attrs']['found']=="n") && (response['mapsearch']['keywords']['correct']['_attrs']['found']=="y")){
						if((response['mapsearch']['keywords']['correct']['_attrs']['corrected']!=undefined) && (response['mapsearch']['keywords']['correct']['_attrs']['corrected']!="")){
							$("search_nearest_what").value  = response['mapsearch']['keywords']['correct']['_attrs']['corrected'];
							searchWord = response['mapsearch']['keywords']['correct']['_attrs']['corrected'];
						}else if((response['mapsearch']['keywords']['correct']['_cdata']!=undefined) && (response['mapsearch']['keywords']['correct']['_cdata']!="")){
							$("search_nearest_what").value  = response['mapsearch']['keywords']['correct']['_cdata'];
							searchWord = response['mapsearch']['keywords']['correct']['_cdata'];
						}
					} 
                
                
                fblock += '<div class="search_results_list">\n';
                
                var filter_options_count = 0; 
                
                if (response['mapsearch']['categories'] != undefined) {
                    
                    var categories = response['mapsearch']['categories']['category'];
                    filter_options_count = categories.length;
                    if (categories.length>1) {
                        show_categories = true;
                    }
		    
                    fblock += '<div class="search_res_header"><h1><strong>Wybierz branżę...</strong></h1></div>\n';
                    
                    if (categories.length>=hide_categories_if_total) {
                        fblock += '<div class="search_results_list_sub_short">\n';
                    }
                    else {
                        fblock += '<div class="search_results_list_sub">\n';
                    }
                    
                    
                    var cat_count=0;
                    var idcat_to_bold = '';
                    for (category_id in categories) {
                        cat_count++;
                        fblock += '<div><a id="search_nearest_select_cat_'+category_id+'" href="#">'+categories[category_id]['name']+'</a><span class="search_results_list_black_number"> ('+categories[category_id]['resultsCount']+')</span></div>\n';
                        if(results_in_category==categories[category_id]['name']){
                              idcat_to_bold = 'search_nearest_select_cat_'+category_id;
                        }
                        if ((cat_count==hide_categories_above) && (categories.length>=hide_categories_if_total)) {
                            fblock += '<div id="search_nearest_select_cat_show_more"><a href="#">więcej branż</a></div>\n';
                            fblock += '</div>\n<div id="search_nearest_select_cat_more" class="search_results_list_sub invisible">\n';
                            }
                    }
                    if (categories.length>=hide_categories_if_total) {
                        fblock += '<div id="search_nearest_select_cat_hide_more"><a href="#">Filtracja wyników</a></div>\n';
                    }
                    fblock += '</div>\n';
                    fblock += '</div>\n<br />\n';
                }
                
		fblock += '<div class="search_res_header"><h1><strong>lub szukaj...</strong></h1></div>'
                if (response['mapsearch']['resultsInName']>0) {
                    fblock += '<div><a id="search_nearest_in_name" href="#">w nazwach firm</a><span class="search_results_list_black_number"> ('+response['mapsearch']['resultsInName']+')</span></div>\n';
                    filter_options_count++;
                }
                if (response['mapsearch']['resultsInOffer']>0) {
                    fblock += '<div><a id="search_nearest_in_offer" href="#">w ofertach</a><span class="search_results_list_black_number"> ('+response['mapsearch']['resultsInOffer']+')</span></div>\n';
                    filter_options_count++;
                }
                if ((response['mapsearch']['resultsInNameAndOffer']>0) && (response['mapsearch']['resultsInOffer']>0) && (response['mapsearch']['resultsInName']>0)) {
                    var sum=Number(response['mapsearch']['resultsInName'])+Number(response['mapsearch']['resultsInOffer']);
                    fblock += '<div><a id="search_nearest_in_nameandoffer" href="#">w nazwach firm i ofertach</a><span class="search_results_list_black_number"> ('+sum+')</span></div>\n';
                    filter_options_count++;
                }

                if (filter_options_count>1)
                    show_filter_flag = true;

                fblock += '</div>\n';
                fblock += '</div>\n';

                $('search_filter_list_box').innerHTML = fblock;
                if(idcat_to_bold!=''&&idcat_to_bold!=undefined){
                  boldSelectedItem(idcat_to_bold);
                }
                if ((BrowserDetect.browser=='Explorer') &&
                    (categories.length>=hide_categories_if_total)) {
                    makeVisible(search_nearest_select_cat_more);
                    makeInvisible(search_nearest_select_cat_more);
                }
                resultsBBnumber= response['mapsearch']['resultsBoundingBoxNumber'];

                if (response['mapsearch']['categories'] != undefined) {
                    for (category_id in categories) {
                        $('search_nearest_select_cat_'+category_id).onclick = partial(onCategorySelected,categories[category_id]['id'], 'search_nearest_select_cat_'+category_id, resultsBBnumber);
                    }

                    if (categories.length>=hide_categories_if_total) {
                        $('search_nearest_select_cat_show_more').onclick = showMoreCategories;
                        $('search_nearest_select_cat_hide_more').onclick = hideMoreCategories;
                    }
                }

                makeInvisible('advert_box');

                if (response['mapsearch']['resultsInName']>0) {
                    $('search_nearest_in_name').onclick = partial(onSearchInSelected,
                                                                  true, false, false, '', false, resultsBBnumber,'search_nearest_in_name');
                }
                if (response['mapsearch']['resultsInOffer']>0) {
                    $('search_nearest_in_offer').onclick = partial(onSearchInSelected,
                                                                   false, true, false, '', false, resultsBBnumber,'search_nearest_in_offer');
                }
                if ((response['mapsearch']['resultsInNameAndOffer']>0) && (response['mapsearch']['resultsInOffer']>0) && (response['mapsearch']['resultsInName']>0)) {
                    $('search_nearest_in_nameandoffer').onclick = partial(onSearchInSelected,
                                                                          true, true, false, '', false, resultsBBnumber,'search_nearest_in_nameandoffer');
                }
            }

            if (show_filter_flag) {
                makeVisible('search_nearest_results_box_header');
            }
            else {
                makeInvisible('search_nearest_results_box_header');
            }

            if (show_categories) {
                makeInvisible('search_results_list_box');
                makeVisible('search_filter_list_box');
                makeInvisible('search_nearest_results_box_header');
            }
            else {
                makeVisible('search_results_list_box');
                makeInvisible('search_filter_list_box');
            }

        }

        if (response.addresses_cnt>1) {
            alt_address_control.updateAlternatives(response.addresses,response.addresses_cnt);
        }
        if (response.pref_addr!=undefined) {
            updateLocation(response.pref_addr);
        }
        else if (response.addresses_cnt>0) {
            updateLocation(response.addresses[0]);
            last_where = search_location.getAddressFull();
        }
        else {
            $("search_nearest_where").value = '';
            search_location.update({});
        }

        if (response.addresses.length!=0 && (response['mapsearch']['companies'] == undefined || response['mapsearch']['companies'] == "")) {
            _optimal_bbox = response.bbox;
            mvfa.fit_bbox(_optimal_bbox.left,_optimal_bbox.top,_optimal_bbox.right,_optimal_bbox.bottom,0.8);
        }
        
        mvfa.pois_clear("poi-r");
        mvfa.pois_set('poi-r',that.getBaseLocationPOI());
        onResize();
    }
    this.onNearestResponse = onNearestResponse;
    $(btn_submit_name).onclick = onSubmitNearestNewSearch;
    $('filter_search_results_switch').onclick = onSwitchFilter;
    this.onSubmitNearestNewSearch = onSubmitNearestNewSearch;

    alt_address_control.onAddressChange = onSubmitNearestNewSearch;
    LocationHintControl('search_nearest_where', 'search_nearest_alt_addresses_box', 'search_nearest_alt_addresses');
    eventMapper.setListener('mv-pois.update.poi-r.search-nearest-center',updateLocation);
    eventMapper.setListener('mv-pois.update.poi-r.search-nearest-center',updateLocation);
}



