/* LAST UPDATE 29/09/2009 */

//<![CDATA[
var mapviewer;
var pan_zoom_widget;
var small_pan_zoom_widget;
var small_zoom_widget;
var map_type_widget;
var location_widget;
var overview_widget;
var tools_widget;
var local_info_widget;

var weather_widget;
var weather_widget_options;

var container;
var max_zindex = 1000;
var searcher, loading, markers, search, address_select, route_finder, route;
var search_address, search_point, bounding_box, min_distance, max_distance, distance_units, submitbtn;
var rfs = ['client_id', 'name', 'street', 'town', 'pc', 'lat', 'lon', 'description', 'url', 'tel', 'opening_hours', 'email', 'fax', 'c10', 'c03', 'c00', 'c11', 'cmpadr', 'c01', 'c02', 'c04', 'c05', 'c12'];
var totalRecordCount = 0;
var lieu_routing;
var lat_addr, lon_addr;
var variable_to_from;
var traitement = 0;

var group_name1 = "group1";

var nb_pages_global;

//PHOADD 20080321
/*
 document.observe("dom:loaded", function(){
 // initially hide all containers for tab content
 onLoad2();
 });
 */
function mm_prev(){
    if (totalRecordCount > 0 && $('select_mm_page').selectedIndex > 0) {
        var p2 = $('select_mm_page').selectedIndex - 1;
		
		$('btn_next_m').setStyle({
        display: 'inline'
    });
        //document.form_mm_nbresult.select_mm_page.selectedIndex = p2;
        $('select_mm_page').options[p2].selected = true;
        if (traitement == 1) {
            traiterformulaire_gotoSearch("", mult_lat1, mult_lon1);
        }
        else {
            traiterformulaire_gotoSearch();
        }
    }
	
}


function mm_next(){
    if (totalRecordCount > 0 && $('select_mm_page').selectedIndex < ($('select_mm_page').options.length - 1)) {
		var p2 = $('select_mm_page').selectedIndex + 1;
		//document.form_mm_nbresult.select_mm_page.selectedIndex = p2;
		$('select_mm_page').options[p2].selected = true;
		
		if (traitement == 1) {
			traiterformulaire_gotoSearch("", mult_lat1, mult_lon1);
		}
		
		else {
			traiterformulaire_gotoSearch();
		}
	//$F('select_mm_page')=$F('select_mm_page')-1;
	}
}

function traiterformulaire(){

    traiterformulaire_gotoSearch();
}




function onLoad(){
	
	/* Event.observe('thetext', 'click', function(){
        seemore();
    }); ajout un onclick a search */
	
	Event.observe('AdvS', 'click', function(){
	 seemore();
	 }); //ajout un onclick a search*/
    
    Event.observe('searchForm', 'submit', function formulaire(){
        traiterformulaire_gotoSearch()
    }); //ajout un onSubmit sur le formulaire
	
    Event.observe('btn_mm_submit', 'click', function formulaire22(){
        //initialisation des valeurs par defaut
        cleanUp();
        /*$('select_mm_page').selectedIndex=0;
         $('select_mm_nbresult').selectedIndex=1;
         $('searchWitin').selectedIndex=0;*/
        if ($('select_mm_page').options[0]) 
            $('select_mm_page').options[0].selected = true;
        if ($('select_mm_nbresult').options[0]) 
            $('select_mm_nbresult').options[0].selected = true;
        /*if ($('searchWitin').options[0]) 
         $('searchWitin').options[0].selected = true;*/
        /*	for(compt=0;compt<$('searchWitin').lenght;compt++){
         if($('searchWitin').options[j].value=="10"){
         $('searchWitin').options[0].selected = true;
         }
         }*/
        //Event.observe('AdvS', 'click', function seemore1(){
        // seemore();
        // }); //ajout un onclick a search*/
		
		/* gestion de l'affichage des boutons suivants et precedants  */
		 
		$('btn_prev_m').setStyle({
        display: 'none'
        });
		 
		/***************************************************************/
		
        traiterformulaire()
    }); //ajout un onSubmit sur le formulaire
	 
    ajouter_txt_onglets();
    
    
    // Construct the route requester with our callback function:
    var funcRef = resultsLoaded_route;
    route_finder = MMFactory.createRouteRequester(funcRef, mapviewer);
    
    
    //Add the map
    mapviewer = new MultimapViewer($('mapviewer'));
	
	//options_group_declutter = new MMDeclutterOptions({ 'hide_index' : true, 'index_title' : 'Select a store' });
	//options_group_icons = new MMIcon("/resources/styles/24_WhereToBuy/images/wheretobuy/group_icons.png") ;
	
	icon_group = new MMIcon("/resources/styles/24_WhereToBuy/images/group_icons.png");
	//icon_group = new MMIcon("/resources/styles/24_WhereToBuy/images/wheretobuy/depart.gif");
	//mapviewer.declutterGroup("",{'cluster_icon': options_group_icons });
	mapviewer.declutterGroup(group_name1,{'hide_index' : true, 'index_title' : 'Select a store', 'cluster_icon' : icon_group});
	//mapviewer.declutterGroup();
	icon_group.iconSize = new MMDimensions(28, 32);
    icon_group.iconAnchor = new MMPoint(0, 0);
	
    //PHOADD
    //mapviewer.goToPosition(new MMLocation("france"));
    address = new MMAddress({
        postcode: "",
        city: "",
        country_code: multimap_country_code
    });
    mapviewer.goToPosition(new MMLocation(address, multimap_default_zoomfactor));
    mapviewer.setOption("units", multimap_locale == "en_GB" ? "miles" : "km");//cf http://www.multimap.com/apidocs/1.2/demos/options.htm
    /*  if (multimap_locale == "en_GB") {
     mapviewer.setScaleBarUnits("miles");
     }else{
     mapviewer.setScaleBarUnits("km");
     }*/
    // mapviewer.goToPosition( new MMLocation( new MMLatLon( 25, 71.0717 ) , 15 ) );
    
    //center_plan();
    
    container = $('widgetcontainer');
    
    //addWeatherWidget(true);
    addPanZoomWidget();
    addOverviewWidget();
    //PHOADD
    //addMapTypeWidget();
    
    // Field.activate('near');
    
    Event.observe('select_mm_nbresult', 'change', function reload(){
        if (traitement == 1) {
            traiterformulaire_gotoSearch("", mult_lat1, mult_lon1);
        }
        else {
            traiterformulaire_gotoSearch();
        }
    }); //ajout un onChange sur le nb de resultats a afficher
    Event.observe('searchWitin', 'change', function reload2(){
        if (traitement == 1) {
            traiterformulaire_gotoSearch("", mult_lat1, mult_lon1);
        }
        else {
            traiterformulaire_gotoSearch();
        }
    }); //ajout un onChange sur la distance max autour du point de depart
    Event.observe('select_mm_page', 'change', function reload3(){
        if (traitement == 1) {
            traiterformulaire_gotoSearch("", mult_lat1, mult_lon1);
        }
        else {
            traiterformulaire_gotoSearch();
        }
    }); //ajout un onChange sur la page selectionn�e
    Event.observe('near', 'click', function reload4(){
        mm_selection();
    }); //ajout un onClik sur le quick search
    Event.observe('near', 'keypress', function valid_form_by_enter(event){
    
        if (event.keyCode == Event.KEY_RETURN) {
            traiterformulaire_gotoSearch();
        }
        
        
    }); //ajout un onkeypress sur le quick search
	
    /* Event.observe('prev', 'click', function add1(){
        mm_prev(); IEB
    }); //ajout un onClik sur le bt prev */
	
	
    Event.observe('btn_next_m', 'click', function add2(){
        mm_next();
    });
	
    Event.observe('btn_prev_m', 'click', function add2(){
        mm_prev();
    });	
    
    
    $('limit').setStyle({
        display: 'none'
    });
    
    $('seeAdress').setStyle({
        display: 'none'
    });
    
    $('useful_infos').setStyle({
        display: 'none'
    });
    
    $('direction').setStyle({
        display: 'none'
    });
/*     $('post_city').setStyle({
        display: 'block'
    }); */
    
    
    mapviewer_2 = $('mapviewer');
    Element.insert(mapviewer_2, "<div id='address_matches' style='display:none'><strong>" + multimap_dico['multimap.search.multiple'] + "</strong><div id='address_select'></div></div>");/*Multiple results found for your input address. Please select one and click 'Search':*/
    /*if (multimap_locale == "en_GB") {
    
     
    
     
    
     
    
     
    
     
    
     Element.update('searchWitin', '<option value="1" selected="selected">1mile</option><option value="10" selected="selected">10miles</option><option value="25" selected="selected">25miles</option><option value="50" selected="selected">50miles</option>');
    
     
    
     
    
     
    
     }*/
    
}

function mm_selection(){
    Form.Element.select('near');
    
}

function cadre_validation(val){

    if (val == true) {
        $('near').setStyle({
            display: 'none'
        });
        $('postcode').setStyle({
            display: 'none'
        });
        $('city').setStyle({
            display: 'none'
        });
    }
    else {
        $('near').setStyle({
            display: 'none'
        });
        $('postcode').setStyle({
            display: 'none'
        });
        $('city').setStyle({
            display: 'none'
        });
    }
}

function seemore(){

    var etat;
    
    if (($('limit').getStyle('display')) == "block") {
    
        etat = true;
        $('near').value = multimap_dico["multimap_gui.search.default"];
        $('postcode').value = "";
        $('city').value = "";
        
        Element.update('AdvS', '<span>' + multimap_dico["multimap.search.advanced"] + '</span>');
        Element.hide('limit');
        Element.hide('seeAdress');
        
        /*	cadre_validation(true)	*/
    }
    else {
        etat = false;
        $('near').value = "";
        Element.update('AdvS', '<span>' + multimap_dico["multimap.search.simple"] + '</span>');
        Element.show('limit');
        Element.show('seeAdress');
        
        /*cadre_validation(false) */
    }
    return etat;
}

function ajouter_txt_onglets(){
    //PHOADD 20080321
    //TabbedPanels1 = Spry.Widget.TabbedPanels("TabbedPanels1");
    Element.update('showing', multimap_dico["multimap.result.showing"]);
    Element.update('results', multimap_dico["multimap.result.results"]);
    Element.update('of', multimap_dico["multimap.result.of"]);
    Element.update('bloccadre_print1', "<li><a id='bloccadre_print1_a' class='print' href='javascript:void(0)' onclick='window.print();'><span>" + multimap_dico['multimap_gui.send.print'] + "</span></a></li>");


    //Element.update('dealer', "<div id='tab1_dealer'></div>");
    //Element.update('tab1_dealer', multimap_dico["multimap.result.dealers"] + '<span id="s">&nbsp;</span>');
	//Element.update('tab1_dealer', multimap_dico["multimap.result.dealers"]);
    
    //Element.update('useful_infos', "<div id='tab2_useful_infos'></div>");
    Element.update('tab2_useful_infos', multimap_dico["multimap.result.informations"]);
	
    //Element.update('direction', "<div id='tab_direction'></div>");
    Element.update('tab_direction', multimap_dico["multimap.result.directions"]);
    
}

function addPanZoomWidget(outside){
    // Add the Pan/Zoom Widget:
    if (!outside) {
        mapviewer.removeWidget(pan_zoom_widget);
        mapviewer.removeWidget(small_pan_zoom_widget);
        mapviewer.removeWidget(small_zoom_widget);
        pan_zoom_widget = new MMPanZoomWidget();
    }
    else {
        removeAllWidgets();
        pan_zoom_widget = new MMPanZoomWidget(new MMBox());
        pan_zoom_widget.setContainer(container);
    }
    mapviewer.addWidget(pan_zoom_widget);
}

function addSmallPanzoomWidget(outside){
    // Add the Small Pan/Zoom Widget:
    if (!outside) {
        mapviewer.removeWidget(pan_zoom_widget);
        mapviewer.removeWidget(small_pan_zoom_widget);
        mapviewer.removeWidget(small_zoom_widget);
        small_pan_zoom_widget = new MMSmallPanZoomWidget();
    }
    else {
        removeAllWidgets();
        small_pan_zoom_widget = new MMSmallPanZoomWidget(new MMBox());
        small_pan_zoom_widget.setContainer(container);
    }
    mapviewer.addWidget(small_pan_zoom_widget);
}

function addSmallZoomWidget(outside){
    // Add the Small Zoom Widget:
    if (!outside) {
        mapviewer.removeWidget(pan_zoom_widget);
        mapviewer.removeWidget(small_pan_zoom_widget);
        mapviewer.removeWidget(small_zoom_widget);
        small_zoom_widget = new MMSmallZoomWidget();
    }
    else {
        removeAllWidgets();
        small_zoom_widget = new MMSmallZoomWidget(new MMBox());
        small_zoom_widget.setContainer(container);
    }
    mapviewer.addWidget(small_zoom_widget);
}

function addMapTypeWidget(outside){
    // Add the Map Type Widget:
    if (!outside) {
        mapviewer.removeWidget(map_type_widget);
        map_type_widget = new MMMapTypeWidget();
    }
    else {
        removeAllWidgets();
        map_type_widget = new MMMapTypeWidget(undefined, new MMBox());
        map_type_widget.setContainer(container);
    }
    mapviewer.addWidget(map_type_widget);
}

function addLocationWidget(outside){
    // Add the Location Widget:
    if (!outside) {
        mapviewer.removeWidget(location_widget);
        location_widget = new MMLocationWidget();
    }
    else {
        removeAllWidgets();
        location_widget = new MMLocationWidget(undefined, new MMBox());
        location_widget.setContainer(container);
    }
    mapviewer.addWidget(location_widget);
}

function addOverviewWidget(outside){
    // Add the Overview Widget:
    if (!outside) {
        mapviewer.removeWidget(overview_widget);
        overview_widget = new MMOverviewWidget();
    }
    else {
        removeAllWidgets();
        overview_widget = new MMOverviewWidget(undefined, undefined, new MMBox());
        overview_widget.setContainer(container);
    }
    mapviewer.addWidget(overview_widget);
}

function addToolsWidget(outside){
    // Add the Tools Widget:
    if (!outside) {
        mapviewer.removeWidget(tools_widget);
        tools_widget = new MMToolsWidget();
    }
    else {
        removeAllWidgets();
        tools_widget = new MMToolsWidget(undefined, new MMBox());
        tools_widget.setContainer(container);
    }
    mapviewer.addWidget(tools_widget);
}

function addLocalInfoWidget(outside){
    // Add the Local Info Widget:
    if (!outside) {
        mapviewer.removeAllOverlays();
        mapviewer.removeWidget(local_info_widget);
        local_info_widget = new MMLocalInfoWidget();
    }
    else {
        removeAllWidgets();
        local_info_widget = new MMLocalInfoWidget(undefined, undefined, new MMBox());
        local_info_widget.setContainer(container);
    }
    mapviewer.addWidget(local_info_widget);
}

function addWeatherWidget(outside){
    // Add the Weather Widget:
    if (!outside) {
        mapviewer.removeAllOverlays();
        mapviewer.removeWidget(weather_widget);
        // Specify default options (unnecessary, but included here for completeness):
        weather_widget_options = {
            'count': 2,
            'show': 'both',
            'tempshow': 'both',
            'units': 'c',
            'wording': 'friendly'
        };
        weather_widget = new MMWeatherWidget(weather_widget_options);
    }
    else {
        // Not required for this example:
        removeAllWidgets();
        weather_widget_options = {
            'count': 5,
            'show': 'both',
            'tempshow': 'both',
            'units': 'both',
            'wording': 'friendly'
        };
        weather_widget = new MMWeatherWidget(weather_widget_options, new MMBox());
        weather_widget.setContainer(container);
    }
    mapviewer.addWidget(weather_widget);
}


var searcher;// = new MMSearchRequester(resultsLoaded);
var search;
var search_point;

var mult_lat1, mult_lon1;

function traiterformulaire_gotoSearch(event, mult_lat, mult_lon){

$('btn_prev_m').setStyle({
			display: 'inline'
		});
$('btn_next_m').setStyle({
			display: 'inline'
		});
		
	/****** gestion des bt next et prev  *******************/	
	if ( $('select_mm_page').selectedIndex == nb_pages_global-1) {
	$('btn_next_m').setStyle({
        display: 'none'
    });	
	$('btn_prev_m').setStyle({
        display: 'inline'
    });				
}
if ($('select_mm_page').selectedIndex==0){
	$('btn_next_m').setStyle({
        display: 'inline'
    });	
	$('btn_prev_m').setStyle({
        display: 'none'
    });	
}

/********************************************/	
	
					
    mult_lat1 = mult_lat;
    mult_lon1 = mult_lon;
    if (Object.isUndefined(mult_lon1)) {
    
        traitement = 0;
    }
    if (searcher == null) {
        searcher = new MMSearchRequester(resultsLoaded);
    }
    
    //search=null;
    if (searcher.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
        cleanMultipleMatches();
    }
    cleanUp();
    loading = $('loading');
    address_select = $('address_select');
    var lieu = Form.Element.getValue('near');
    lieu_routing = lieu;
    var distance = Form.Element.getValue('searchWitin');
    var code_postal = Form.Element.getValue('postcode');
    var ville = Form.Element.getValue('city');
    var taille_liste = Form.Element.getValue('select_mm_nbresult');
	
		if ($('select_mm_nbresult').options[2].selected==true) //si on selectionne "tout" pour le nb de resultats
            taille_liste = totalRecordCount;
			
	
    var selected_page = Form.Element.getValue('select_mm_page');
    loadingStatus(false);
    page = $('select_mm_page');
    
    if (totalRecordCount > 0) {
    
        while (totalRecordCount < ((selected_page - 1) * taille_liste - 1)) {
            selected_page = selected_page - 1;
        }
    }
    
    if ((code_postal != "") || (ville != "")) {
    
        search_point = null;
        address = new MMAddress({
            postal_code: code_postal,
            city: ville,
            street: lieu,
            country_code: multimap_country_code
        });
        if (search == null || search.point != null) {
            search = new MMSearch(address);
        }
        else {
            search.address = address;
        }
        
    }
    else 
        if (!Object.isUndefined(event)) {
            //var element = Event.element(event);
            //search.address = new MMAddress({
            //        coords:element.coords,
            //        country_code: multimap_country_code
            //    });
            //search.point=element.coords;
            search_point = new MMLatLon(0, 0);
            /* search_point.lat = this.coords.lat;
         search_point.lon = this.coords.lon;*/
            search_point.lat = mult_lat;
            search_point.lon = mult_lon;
            if (search == null || search.point == null) {
                search = new MMSearch(search_point);
            }
            else {
                search.point = search_point;
            }
        }
        else {
            var rfs = ['id', 'client_id', 'country', 'name', 'street', 'town', 'pc', 'lat', 'lon', 'description', 'url', 'tel', 'opening_hours', 'email', 'fax', 'c10', 'c03', 'c00', 'c11', 'cmpadr', 'c01', 'c02', 'c04', 'c05', 'c12'];
            
            // mapviewer.goToPosition(new MMLocation(lieu));
            /*
         if (address_select.options &&  address_select.options.length > 1) {
         var coords = address_select.options[address_select.selectedIndex].value.split(',');
         search.point = new MMLocation(new MMLatLon(coords[0], coords[1]));
         } else if (address_qs.value != '') {
         search.address = new MMAddress({ qs : address_qs.value, country_code : country_code.value});
         } else {
         search.point = mapviewer.getCurrentPosition();
         }
         if (bounding_box.checked) {
         search.bounding_box = mapviewer.getMapBounds();
         }
         if (max_distance.value != '') {
         search.max_distance = Number(max_distance.value);
         }
         if (min_distance.value != '') {
         search.min_distance = Number(min_distance.value);
         }
         if (count.value != '') {
         search.count = Number(count.value);
         }
         if (start_index.value != '') {
         search.start_index = Number(start_index.value);
         }*/
            //search.address = new MMAddress({ qs : lieu});
            search_point = null;
            address = new MMAddress({
                qs: lieu,
                country_code: multimap_country_code
            });
            if (search == null || search.point != null) {
                search = new MMSearch(address);
            }
            else {
                search.address = address;
            }
        }
    //  var etat_search = seemore();
    //var rfs = ['client_id'];
    search.start_index = Number(((Number(selected_page) - 1) * Number(taille_liste)) + 1);
    //search.start_index = 1;
    search.count = taille_liste;
    //if(totalRecordCount==0)
    //	search.result_set_size = taille_liste ;
    //else
    //	search.result_set_size = totalRecordCount ;
    search.result_set_size = selected_page * taille_liste;
    
    search.return_fields = rfs;
    if (multimap_locale == "en_GB") {
        search.radius_units = 'miles';
    }
    else {
        search.radius_units = 'km';
    }
    search.route_modes = 'driving';
    // Activate the next line of code if you wish to configure the API to use data
    // from one of your existing 'classic' Multimap services (such as XML Storefinder), 
    // as described in the topic "Integration with Classic Multimap XML Products".  
    // When doing so, please replace "[api_key]" with the appropriate service client name:
    search.data_source = multimap_country_datasource;
    search.order_by_fields = 'distance'; //'name';
    search.order_by_order = 'asc';
    //search.result_set_size = result_set_size.value;
    
    search.max_distance = Number(distance);
    if (multimap_locale == "en_GB") {
        search.distance_units = 'miles';
    }
    else {
        search.distance_units = 'km';
    }
    var tab = new Array();
    tab = mm_so_get_custom_fields();
    
    var i_tab = 0;
    var filters = [];
    search.filters = new Array();
    
    
    if (typeof multimap_search_logical_operator == "undefined") {
        search.logic = "OR";
    }
    else 
        if (multimap_search_logical_operator == "AND") {
            search.logic = "AND";
        }
    while (tab[i_tab] != null) {
    
        search.filters.push(new MMSearchFilter(tab[i_tab], 'eq', 1));
        i_tab++;
    }
    
    mapviewer.setMarkerFilters(filters);
    
    
    try {
        //search.address = new MMAddress({ city : lieu, country_code : multimap_country_code});
        setTimeout("loadingStatus(true)", 1);
        setTimeout("timedSearch();", 2);
    } 
    catch (error) {
        alert("Erreur javascript");
        alert("Nom de l'exception: " + error.name);
        alert("Message de l'exception levee: " + error.message);
    }
    
}

function timedSearch(){
    try {
        //search.address = new MMAddress({ city : lieu, country_code : multimap_country_code});
        //loadingStatus(true);
        searcher.search(search);
    } 
    catch (error) {
        alert("Erreur javascript");
        alert("Nom de l'exception: " + error.name);
        alert("Message de l'exception levee: " + error.message);
    }
}

function loadingStatus(bool){
    // If we're loading values we want to disable the form elements
    // and display a spinning icon to show activity
    //  bounding_box.disabled = bool;
    //min_distance.disabled = bool;
    // max_distance.disabled = bool;
    
    btn_mm_submit = $('btn_mm_submit');
    btn_mm_submit.disabled = bool;
    
    lieu = $('near');
    lieu.disabled = bool;
    
    searchWitin = $('searchWitin');
    searchWitin.disabled = bool;
    
    select_mm_nbresult = $('select_mm_nbresult');
    select_mm_nbresult.disabled = bool;
    
    select_mm_page = $('select_mm_page');
    select_mm_page.disabled = bool;
    

	
    /*prev_m = $('btn_prev_m');
     prev_m.disabled = bool;
     
     btn_next_m = $('btn_next_m');
     btn_next_m.disabled = bool;
     
     prev = $('prev');
     prev.disabled = bool;
     
     btn_next = $('btn_next_m');
     btn_next.disabled = bool;*/
    /*Event.observe('prev', 'click', function add1(){
     while(bool == true )wait();
     }); //ajout un onClik sur le bt prev
     Event.observe('btn_next_m', 'click', function add2(){
     while(bool == true )wait();
     }); //ajout un onClik sur le bt next*/
    loading.style.display = bool ? 'block' : 'none';
    
}


function handleRecord(record, num, container){

    if (multimap_locale == "en_GB") {
        var unite_long = " miles";
        var dist_lang = record.distance.miles;
    }
    else {
        var unite_long = " km";
        var dist_lang = record.distance.km;
    }
    
    var chaine_url = "";
    if (record.url == "") {
        chaine_url = '<a href="javascript:void(0)"></a>'
    }
    else {
        //PHOADD 20080321
        chaine_url = '<a target="blank" href="' + (record.url.toLowerCase().substring(0, 7) == "http://" ? record.url : "http://" + record.url) + '"><img border="0" src="/resources/styles/24_WhereToBuy/images/loupe.gif" >';
    }
    
    
    var img = "";
    
    
    if (multimap_locale == "de_DE") {
        if ((record.c00 == 1) || (record.c03 == 1) || (record.c10 == 1) || (record.c11 == 1)) {
            img += "<div class='img_results_multimap'>";
            if (record.c00 == 1) {
                img += "<img src='/resources/styles/24_WhereToBuy/images/localized/" + multimap_locale + "/C00.gif' >";
            }
            if (record.c03 == 1) {
                img += "<img src='/resources/styles/24_WhereToBuy/images/localized/" + multimap_locale + "/C03.gif' >";
            }
            if (record.c10 == 1) {
                img += "<img src='/resources/styles/24_WhereToBuy/images/localized/" + multimap_locale + "/C10.gif' >";
            }
            if (record.c11 == 1) {
                img += "<img src='/resources/styles/24_WhereToBuy/images/localized/" + multimap_locale + "/C11.gif' >";
            }
            img += "</div>";
        }
    }
    var affich_adresse_results = "";
    if ((multimap_locale == "de_DE") || (multimap_locale == "sl_SI") || (multimap_locale == "nl_NL") || (multimap_locale == "de_AT")) { // Germany, Austria, Slovenia and Holland.
        affich_adresse_results = "style='display:block'";
    }
    
    var anchor = '<tr><td class="rank">' + num + '</td><td class="name"><a ';
    anchor += ' href="#mapviewer" ';
    anchor += ' record_id="' + record.id + '" ';
    anchor += ' id="anchor_' + record.id + '" ';
    anchor += ' >';
    anchor += '</a></td><td class="type"><div id="description">' + record.description + '</div>' + img + '<div class="adresse_print" ' + affich_adresse_results + '>' + record.street + '&nbsp;' + record.pc + '&nbsp;' + record.town + '</div></td><td class="distance">' + dist_lang + unite_long + '</td>';
    
    // anchor += '<td style="text-align:right">' + chaine_url + '</td>';
    // anchor += '<td style="text-align:right"></td>';
    
    if (multimap_locale == "en_GB") {
        for (i = 0, j = 0; i < rfs.length; i++) {
            if (record[rfs[i]]) {
                if (j > 0) 
                    markerText += ', ';
                // Create marker text for the infobox for this record:    
                var markerText = '<h1>' + record[rfs[1]] + '<' + '/h1><div class="img_infobox">' + img + '</div><strong class="desc">';
                markerText += record[rfs[7]] + '</strong><br />'; //description
                markerText += record[rfs[17]] + '<br />'; //complement d'adresse cmpadr
                markerText += '<p>';
                markerText += record[rfs[2]] + '<br />';//street
                markerText += record[rfs[3]] + '<br />';//town
                markerText += record[rfs[4]];//postcode
                var addr = "";
                addr += record[rfs[2]] + ' ' + record[rfs[4]] + ' ' + record[rfs[3]];
                
                var lat_addr = record.point.lat;
                var lon_addr = record.point.lon;
                // adresse, lat, long
                markerText += '<div id="direction_from"><a href="#TabbedPanels1" onclick="direction_from(\'' + addr + '\',' + lat_addr + ',' + lon_addr + ')">' + multimap_dico["multimap.result.direction.from_the_dealer"] + '</div></a>';
                markerText += '<div id="direction_to"><a href="#TabbedPanels1" onclick="direction_to(\'' + addr + '\',' + lat_addr + ',' + lon_addr + ')">' + multimap_dico["multimap.result.direction.to_the_dealer"] + '</div></a>';
                //alert(record[rfs[i]]);
                
                // anchor +='<td>'+record[rfs[i]]+'</td>';
                j++;
            }
        }
    }
    else 
        if (multimap_locale == "fr_FR") {
            for (i = 0, j = 0; i < rfs.length; i++) {
                if (record[rfs[i]]) {
                    if (j > 0) 
                        markerText += ', ';
                    // Create marker text for the infobox for this record:    
                    var markerText = '<h1>' + record[rfs[1]] + '<' + '/h1><div class="img_infobox">' + img + '</div><strong class="desc">';
                    markerText += record[rfs[7]] + '</strong><br />'; //description
                    markerText += record[rfs[17]] + '<br />'; //complement d'adresse cmpadr
                    markerText += '<p>';
                    markerText += record[rfs[2]] + '<br />';//street
                    markerText += record[rfs[3]] + '&nbsp;';//town
                    markerText += record[rfs[4]];//postcode
                    var addr = "";
                    addr += record[rfs[2]] + ' ' + record[rfs[4]] + ' ' + record[rfs[3]];
                    
                    var lat_addr = record.point.lat;
                    var lon_addr = record.point.lon;
                    // adresse, lat, long
                    markerText += '<div id="direction_from"><a href="#TabbedPanels1" onclick="direction_from(\'' + addr + '\',' + lat_addr + ',' + lon_addr + ')">' + multimap_dico["multimap.result.direction.from_the_dealer"] + '</div></a>';
                    markerText += '<div id="direction_to"><a href="#TabbedPanels1" onclick="direction_to(\'' + addr + '\',' + lat_addr + ',' + lon_addr + ')">' + multimap_dico["multimap.result.direction.to_the_dealer"] + '</div></a>';
                    //alert(record[rfs[i]]);
                    
                    // anchor +='<td>'+record[rfs[i]]+'</td>';
                    j++;
                }
            }
        }
        else {
            for (i = 0, j = 0; i < rfs.length; i++) {
                if (record[rfs[i]]) {
                    if (j > 0) 
                        markerText += ', ';
                    // Create marker text for the infobox for this record:    
                    var markerText = '<h1>' + record[rfs[1]] + '<' + '/h1><div class="img_infobox">' + img + '</div><strong class="desc">';
                    markerText += record[rfs[7]] + '</strong><br />'; //description
                    markerText += record[rfs[17]] + '<br />'; //complement d'adresse cmpadr
                    markerText += '<p>';
                    markerText += record[rfs[2]] + '<br />';//street
                    markerText += record[rfs[4]] + '<br />';//postcode
                    markerText += record[rfs[3]] + '<br />';//town
                    var addr = "";
                    addr += record[rfs[2]] + ' ' + record[rfs[4]] + ' ' + record[rfs[3]];
                    
                    var lat_addr = record.point.lat;
                    var lon_addr = record.point.lon;
                    // adresse, lat, long
                    markerText += '<div id="direction_from"><a href="#TabbedPanels1" onclick="direction_from(\'' + addr + '\',' + lat_addr + ',' + lon_addr + ')">' + multimap_dico["multimap.result.direction.from_the_dealer"] + '</div></a>';
                    markerText += '<div id="direction_to"><a href="#TabbedPanels1" onclick="direction_to(\'' + addr + '\',' + lat_addr + ',' + lon_addr + ')">' + multimap_dico["multimap.result.direction.to_the_dealer"] + '</div></a>';
                    //alert(record[rfs[i]]);
                    
                    // anchor +='<td>'+record[rfs[i]]+'</td>';
                    j++;
                    
                }
            }
        }
    markerText += '<' + '/p>';
    anchor += '</tr>';
    
    /*if (record.distance) {
     markerText += '<p>Distance: ' + record.distance.km + ' km, ' + record.distance.miles + ' mi<' + '/p>'
     }*/
    var phone = multimap_dico["multimap.result.tel"] + '&nbsp;:';
    var fax = multimap_dico["multimap.result.fax"] + '&nbsp;:';
    var email = multimap_dico["multimap.result.email"] + '&nbsp;:';
    var opening_hrs = multimap_dico["multimap.result.opening_hrs"] + '&nbsp;:';
    var link_site = multimap_dico["multimap.result.url"];
    var link = '<a target="blank" href="' + (record.url.toLowerCase().substring(0, 7) == "http://" ? record.url : "http://" + record.url) + '">' + link_site + '</a>';
    var general = multimap_dico["multimap.result.general"];
    var seemore = multimap_dico["multimap.result.seemore"];
    
    //customized marker
    var icon = new MMIcon('/resources/styles/24_WhereToBuy/images/icn_nikon2.png');
    icon.iconSize = new MMDimensions(23, 26);
    icon.iconAnchor = new MMPoint(0, 0);
	icon.groupName = group_name1; 
    
    if (record.point) {
        var marker = mapviewer.createMarker(new MMLocation(record.point), {
            'text': num,
            'icon': icon
        });
        
        for (i = 0, j = 0; i < rfs.length; i++) {
            if (record[rfs[i]]) {
                if (j > 0) 
                    var markerText2 = "<h1>" + record[rfs[1]] + "</h1><strong class='desc'>" + record[rfs[7]] + "</strong><br />";
                
                if (record.tel != "") {
                    markerText2 += phone + "&nbsp;" + record.tel + "<br />";
                }
                if (record.email != "") {
                    markerText2 += email + "&nbsp;" + record.email + "<br />";
                }
                if (record.fax != "") {
                    markerText2 += fax + "&nbsp;" + record.fax + "<br />";
                }
                if ((record.opening_hours != "") && (record.opening_hours != null)) {
                    markerText2 += opening_hrs + "&nbsp;" + record.opening_hours + "<br />";
                }
                if (record.url != "") {
                    markerText2 += link;
                }
                j++;
            }
        }
        
        /*****   infobox with 2 tabs      *************/
        
        var tabs = [new MMInfoBoxTab(general, markerText), new MMInfoBoxTab(seemore, markerText2), ];
        marker.setInfoBoxContent(tabs);
        
        /*****************************************************/
        
        //   marker.setInfoBoxContent('<p>' + markerText + '<' + '/p>');
        markers.push(marker);
    }
    // Show the name in our records list. When the name is clicked, open
    //  our info box:    
    //var anchor = document.createElement('a');
    // anchor.href = '#';
    //anchor.record_id = record.id;
    //anchor.appendChild(document.createTextNode(record.name));
    //anchor.onclick = function(){
    //    openInfoBox('click', marker);
    //    return false;
    //};
    
    Element.insert(container, anchor);
    var anchor = $('anchor_' + record.id);
    // var anchor_img = $('anchor_img_' + record.id);
    
    Element.update(anchor, record.name);
    //anchor.onclick = function(){
    //    openInfoBox('click', marker);
    //    return false;
    //};
    anchor.marker = marker;
    anchor.observe('click', function(event){
        //alert(Event.element(event).innerHTML);
        var marker = Event.element(event).marker;
        marker.openInfoBox();
        return false;
    });
    
    return anchor;
    
	
}

function direction_to(chaine_addr, lat, lon){
	document.getElementById('direction').style.fontWeight='bold';
	document.getElementById('dealer').style.fontWeight='normal';

    cleanUp_routing();
    
    $('direction').setStyle({
        display: 'block'
    });
    lat_addr = lat;
    lon_addr = lon;
    $('direction').className = 'TabbedPanelsTab TabbedPanelsTabSelected';
    $('dealer').className = 'TabbedPanelsTab';
    $('direction_div').setStyle({
        display: 'block'
    });
    $('dealer_div').setStyle({
        display: 'none'
    });
    lieu_routing = chaine_addr;
    Element.update('left_routing', "<div class='interne-routing'><form id='routingForm' action='#' method='POST'><label for='addr_saisie'>" + multimap_dico['multimap.result.direction.from'] + "</label> <input type='text' id='addr_saisie' /> <div class='hidden' id='matches1'><select id='select1'></select></div> <div class='drive-routing'><label for='driving'></label><input type='radio' checked='checked' name='mode' id='driving' />" + multimap_dico['multimap.result.direction.driving'] + "<label for='walking'></label><input type='radio' name='mode' id='walking' />" + multimap_dico['multimap.result.direction.walking'] + "<input type='button' onclick='callRoute()' value='Go' id='submitbtn' /></div></div>");
    Element.update('right_routing', "<div class='interne-routing PositionTxt'>" + multimap_dico['multimap.result.direction.to'] + "&nbsp;:<strong>" + lieu_routing + "</strong></div>");
    Event.observe('addr_saisie', 'keypress', function (event){
      callRouteIfReturn(event);
    });
    
    variable_to_from = 1;
    Element.update('bloccadre_print1', "<li><a target='_blank' class='print' href='/resources/styles/24_WhereToBuy/images/objects/multimap_print_routing.html'><span>" + multimap_dico['multimap_gui.send.print'] + "</span></a></li>");
    window.location.hash = "direction";
}

function direction_from(chaine_addr, lat, lon){
	document.getElementById('direction').style.fontWeight='bold';
	document.getElementById('dealer').style.fontWeight='normal';

    cleanUp_routing();
    $('direction').setStyle({
        display: 'block'
    });
    lat_addr = lat;
    lon_addr = lon;
    $('direction').className = 'TabbedPanelsTab TabbedPanelsTabSelected';
    $('dealer').className = 'TabbedPanelsTab';
    $('direction_div').setStyle({
        display: 'block'
    });
    $('dealer_div').setStyle({
        display: 'none'
    });
    
    lieu_routing = chaine_addr;
    Element.update('left_routing', "<div class='interne-routing PositionTxt'>" + multimap_dico['multimap.result.direction.from'] + "&nbsp;:<strong>" + lieu_routing + "</strong></div>");
    Element.update('right_routing', "<div class='interne-routing'><form method='' action=''><label for='addr_saisie'>" + multimap_dico['multimap.result.direction.from'] + "</label> <input type='text' id='addr_saisie' /> <div class='hidden' id='matches1'><select id='select1'></select></div> <div class='drive-routing'><label for='driving'></label><input type='radio' checked='checked' name='mode' id='driving' />" + multimap_dico['multimap.result.direction.driving'] + "<label for='walking'></label><input type='radio' name='mode' id='walking' />" + multimap_dico['multimap.result.direction.walking'] + "<input type='button' onclick='callRoute()' value='Go' id='submitbtn' /></div></div>");
    Event.observe('addr_saisie', 'keypress', function (event){
      callRouteIfReturn(event);
    });    
	
    variable_to_from = 0;
    Element.update('bloccadre_print1', "<li><a target='_blank' href='/resources/styles/24_WhereToBuy/images/objects/multimap_print_routing.html' class='print'><span>" + multimap_dico['multimap_gui.send.print'] + "</span></a></li>");
    window.location.hash = "direction";
}

function callRouteIfReturn(event) {
	if (event.keyCode == 13) {
	  callRoute();
	  return false;
	}
	return true;
}

function resultsLoaded_route(){

    if (route.error_code) {
        if (route.error_code == 'MM_ROUTE_GEOCODING_ERRORS') {
            // Handle geocoding errors by displaying disambiguation dropdowns
            processGeocodingErrors_routing(route.geocoding_errors);
        }
        else {
            // Display an error message, if applicable:
            alert(route.error_code + ': ' + route.error_explanation);
        }
    }
    else {
        // use getAutoScaleLocation to show the entire route on the map, with the route bounds:
        mapviewer.goToPosition(mapviewer.getAutoScaleLocation(route.bounds));
        displayStages(route);
        // Show the route on the map with PolyLines, by adding each polyline returned:
        for (var i = 0, l = route.polyLine.length; i < l; ++i) {
            mapviewer.addOverlay(route.polyLine[i]);
            Element.insert('widgets_right', "<div id='info_route_key'>" + route.key + "</div>");
            
        }
    }
    loadingStatus(false);
}

function resultsLoaded(){
    //PHOADD 20080321
    //loadingStatus(false);
    
    var total = 0;
    var start_index_value = search.start_index;
    
    //PHOADD
    if (searcher.record_sets[0] && searcher.record_sets[0].records && searcher.record_sets[0].records.length > 0) {
    
        $('widgetcontainer').setStyle({
            display: 'block'
        });
		$('Cadre_P').setStyle({
            display: 'block'
        });
        
        $('result_search').setStyle({
            display: 'block'
        });
        
        total = searcher.record_sets[0].totalRecordCount;
        var point = searcher.record_sets[0].records[0].point;
        var mmLocation = new MMLocation(point, multimap_default_zoomfactor);
        mapviewer.goToPosition(mmLocation);
    }
    else {
        //mapviewer.goToPosition ??
    }
    totalRecordCount = total;
    
    //return;
    // Process search results
    var container = $('recordListDiv');
    //PHOADD 20080321
    //loadingStatus(false);
    
    var nomatches = total == 0;
    
    if (searcher.error_code) {
        if (searcher.error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
            traitement = 1;
            processGeocodingErrors(searcher.result_set);
            //mapviewer.goToPosition ??
            //PHOADD 20080321
            nomatches = false;
            //PHOADD 20080325
            return;
        }
        else 
            if (searcher.error_code == 'MM_GEOCODE_NO_MATCHES') {
                nomatches = true;
                
            }
            else {
                alert(searcher.error_code + ': ' + searcher.error_explanation);
                //PHOADD 20080321
                nomatches = false;
                
            }
        //PHOADD 20080321
        //return;
    }
    if (nomatches) {
        if (search_point) 
            mapviewer.goToPosition(new MMLocation(search_point, multimap_default_zoomfactor));
        
        Element.update('alert1', "<img src='/resources/styles/24_WhereToBuy/images/alert.png' border='0' />&nbsp;" + multimap_dico['multimap.search.no_result']);
        //Effect.Pulsate('alert1');
        $('alert1').setStyle({
            display: 'block'
        });
        
        
        
        //alert(multimap_dico['multimap.search.no_result'].unescapeHTML());
    
    }
    //PHOADD Element.update('nb_resultats',searcher.record_sets[0].records.length);
    Element.update('nb_resultats', total);
    //Element.update('titles_onglets', "<table class='searchResult2'><tr><td class='rank' id='num_record'>#</td><td class='name' id='dealer_name'>Dealer Name</td><td class='type'>Adress</td><td class='distance'>Distance</td></tr></table>");
    //Element.update('num_record', multimap_dico['multimap.result.dealers.id']);
    //Element.update('link', multimap_dico['multimap.result.dealers.link']);
    //Element.update('distance', multimap_dico['multimap.result.dealers.distance']);
    //Element.update('dealer_name', multimap_dico['multimap.result.dealers.name']);
    Element.update('mm_page', multimap_dico['multimap.result.page']);
    Element.update('of2', multimap_dico['multimap.result.of']);
    
    Element.update('s', '&nbsp;(' + total + ')');
    
    
    var nb_pages2 = (total) * (1 / search.count);
    var nb_pages = Math.ceil(nb_pages2);
	nb_pages_global = nb_pages;
    var choixpage = $('select_mm_page');
    selected = Form.Element.getValue('select_mm_page');
    
    Element.update('nb_resultats_page', nb_pages);

	if(nb_pages_global == 1){
	$('btn_next_m').setStyle({
        display: 'none'
    });	
	$('btn_prev_m').setStyle({
        display: 'none'
    });	
}
	
    //while (total < (nb_pages * search.count)) {
    //nb_pages=nb_pages-1;
    //}
    
    choixpage.options.length = 0;
    choixpage.options.length = nb_pages;
    
    selected = Math.floor(search.start_index / search.count) + 1;
    selection = 1;
    for (i = 0; i < nb_pages; i++) {
    
        choixpage.options[i].value = i + 1;
        choixpage.options[i].text = i + 1;
        if (selected == choixpage.options[i].text) {
            //PHOADD 20080321
            choixpage.options[i].selected = true;
            selection = i;
        }
    }
    
    //PHOADD 20080321
    //choixpage.options.selectedIndex = selection;
    
    //PHOADD 20080322
    //setTimeout("loadingStatus(false)",1);
    loadingStatus(false);
    
    // text="<option >1</option><option >2</option><option selected='selected'>3</option><option>4</option>";
    // Element.update('select_mm_page',text);
    
    
    /* Event.observe('AdvS', 'click', function seemore1(){
     seemore();
     }); //ajout un onclick sur le <a> de chaque resultat*/
    // nb_resultats=searcher.record_sets.length;
    //var results_returned = searcher.record_sets.length;
    
    //  Create table and table header     
    //var el = document.createElement('table');
    //el.id = 'recordList';
    var el = Element.insert(container, '<tr></tr>')

    var tbody = $('recordListDiv');
    
    
    var start_index_value = 1;
    if (search.start_index && Number(search.start_index) > 0) {
        start_index_value = Number(search.start_index);
    }
    // var tr_first = document.createElement('tr');
    // var tr_first = Element.insert(tbody,'<tr></tr>');
    /*var ths = [document.createTextNode('#'), document.createTextNode(multimap_dico["multimap.result.dealers.name"]), document.createTextNode(multimap_dico["multimap.result.dealers.distance"]), document.createTextNode(multimap_dico["multimap.result.dealers.link"]),    /*  document.createTextNode ( 'Straight line distance (km/mi)' ), 
     document.createTextNode ( 'Driving distance (km/mi)' ),
     document.createTextNode ( 'Driving duration (dd:hh:mm)' ),
     document.createTextNode ( 'Walking distance (km/mi)' ),
     document.createTextNode ( 'Walking duration (dd:hh:mm)' )*/
    //  ];
    /* for (i = 0; i < ths.length; i++) {
     var th = document.createElement('th');
     var tr_first = Element.insert(tbody,'<tr></tr>');
     th.appendChild(ths[i]);
     tr_first.appendChild(th);
     }*/
    //    tbody.appendChild(tr_first);
    
    // for each record set
    
    for (var count = 0, l = searcher.record_sets.length; count < l; count++) {
    
        // for each record
        if (searcher.record_sets[count].error) {
            var err = '';
            if (searcher.record_sets[count].error.error_explanation) {
                err = searcher.record_sets[count].error.error_explanation;
            }
            else {
                //PHOADD 20080322 � localiser
                err = 'Your request failed. Error code: ' + searcher.record_sets[count].error.error_code;
            }
            alert(err);
            //PHOADD 20080322
            //return;
            break;
        }
        
        if (searcher.record_sets[count].records) {
            for (var record_count = 0, rl = searcher.record_sets[count].records.length; record_count < rl; record_count++) {
                var record = searcher.record_sets[count].records[record_count];
                var tr = handleRecord(record, start_index_value + record_count, tbody);
                //var tr = handleRecord(record, record_count,tbody);
            
            }
            mapviewer.goToPosition(mapviewer.getAutoScaleLocation(markers));
            //mapviewer.declutterGroup();
        }
        
        
    }
    
    
    
}


function createPages(records_per_page, total_records, selected_page){

    while (page.firstChild) {
        page.removeChild(page.firstChild);
    }
    
    //Build dropdown for pages:
    for (i = 0; i * records_per_page <= total_records; i++) {
        var el = document.createElement('option');
        el.value = i + 1;
        el.appendChild(document.createTextNode(i + 1));
        page.appendChild(el);
    }
    // index starts at 0, so use 'selected_page - 1' to determine which option should show as selected:
    page.selectedIndex = selected_page - 1;
    paginationStatus(false);
    
}

function newSearch(){
    // Set selected page back to first one, as the number of valid pages
    //  will be different with a different count per page:
    page.selectedIndex = 0;
    initSearch();
}

function processGeocodingErrors(result_set){
    traitement = 1;
    var mult_choice = "";
    Element.update('address_select', "");
    for (var j = 0; j < result_set.length; j++) {
        var displayName = result_set[j].address.display_name;
        
        var lat = result_set[j].coords.lat;
        var lon = result_set[j].coords.lon;
        
        
        var point = result_set[j].coords.copy();
        
        var id_choice = "mm_item_choice_" + j;
        
        mult_choice = '<a href="javascript:void(0)" ><span id="' + id_choice + '" onclick=traiterformulaire_gotoSearch("null",' + lat + ',' + lon + ') >' + displayName + '</span></a>';
        
        Element.insert('address_select', mult_choice);
        
        var obj_choice = $(id_choice);
        
        obj_choice.display_name = displayName;
        
        obj_choice.coords = point;
        //Element.update('near',obj_choice.display_name);
        //$('near').value=displayName;
        //Event.observe(id_choice, 'click', traiterformulaire_gotoSearch);
        /*var option = document.createElement('option');
         option.value = point.lat + ',' +point.lon;
         option.appendChild(document.createTextNode(displayName));
         address_select.appendChild(option);
         address_select.selectedIndex=0; */
    }
    //Element.update('address_select',mult_choice);
    $('address_matches').style.display = 'block';
    
}

function processGeocodingErrors_routing(errors){
    for (var i = 0; i < errors.length; i++) {
        if (errors[i].error_code == 'MM_GEOCODE_NO_MATCHES') {
            alert('No matching locations for Location ' + errors[i].input_id);
        }
        else 
            if (errors[i].error_code == 'MM_GEOCODE_MULTIPLE_MATCHES') {
                var select = $('select1');
                
                for (var j = 0; j < errors[i].results.length; j++) {
                    var displayName = errors[i].results[j].address.display_name;
                    var point = errors[i].results[j].coords;
                    var option = document.createElement('option');
                    option.value = point.lat + ',' + point.lon;
                    option.appendChild(document.createTextNode(displayName));
                    select.appendChild(option);
                    select.selectedIndex = 0;
                }
                
                $('matches1').style.display = 'block';
                $('addr_saisie').style.display = 'none';
            }
    }
}

function addLocation(num, locations){
    var qs = $('addr_saisie');
    //  var country_code = document.getElementById('country_code' + num);
    var select = $('select1');
    var address = new MMAddress();
    
    if (select.options && select.options.length > 1) {
        var coords = select.options[select.selectedIndex].value.split(',');
        locations.push(new MMLocation(new MMLatLon(coords[0], coords[1])));
    }
    else {
        if (qs.value != '') {
            address.qs = qs.value;
            address.country_code = multimap_country_code;
        }
        locations.push(new MMLocation(address));
    }
}

function callRoute(){

    cleanUp_routing();
    
    var add_r = $('addr_saisie').value;
    
    // Add the 3 waypoints for our route from London to Guildford via Reading:
    var locations = new Array();
    
    
    if (variable_to_from == 0) { //direction_from
        // Add location with coordinates depart
        locations.push(new MMLocation(new MMLatLon(lat_addr, lon_addr)));
        
        // Add location with coordinates for end
        /*locations.push(new MMAddress({
         qs: add_r,
         country_code: multimap_country_code
         }));*/
        addLocation(1, locations);
        // locations.push(new MMLocation(new MMLatLon(48.855, 2.36864)));
    }
    else { //direction_to
        // Add location with coordinates for end
        /*locations.push(new MMAddress({
         qs: add_r,
         country_code: multimap_country_code
         }));*/
        addLocation(1, locations);
        
        locations.push(new MMLocation(new MMLatLon(lat_addr, lon_addr)));
    }
    // Disable form inputs, and display spinning icon until route is loaded:
    //  loadingStatus( true );
    
    /* */
    // addLocation(2, locations);
    
    // Construct route:
    route = new MMRoute(locations);
    /*route.routeStartLabel=A;
     route.routeColor="#000";*/
    // Based on selection, set the mode for the route as 'walking' or 'driving':
    var walking = $('walking').checked;
    if (walking == true) {
        route.mode = 'walking';
    }
    else {
        route.mode = 'driving';
    }
    /* route.exclude = '';*/
    // Based on the selection, specify the language for the travel directions to be returned in:
    /* var lang = document.getElementById('lang') [document.getElementById('lang').selectedIndex].value;
     if (lang != '' ) { route.lang = "fr"; }  */
    //route.lang = current_lang;
    
    //route.lang = "fr";
    if (multimap_language == "fr" || multimap_language == "es" || multimap_language == "de" || multimap_language == "da" || multimap_language == "pt" || multimap_language == "sv" || multimap_language == "no" || multimap_language == "nl" || multimap_language == "en_GB" || multimap_language == "en" || multimap_language == "en_US") {
        route.lang = multimap_language;
    }
    else {
        route.lang = "en";
    }
    // Use Convenience API to request the route:  
    
    route_finder.request(route);
    
}

function cleanMultipleMatches(){
    while (address_select.firstChild) {
        address_select.removeChild(address_select.firstChild);
    }
    $('address_matches').style.display = 'none';
    
    var qs = $('addr_saisie');
    var select = $('select1');
    var matches = $('matches');
    if (select) {
        while (select.firstChild) {
            select.removeChild(select.firstChild);
        }
    }
    if (qs) 
        qs.value = '';
    if (matches) 
        matches.style.display = 'none';
    //  if(addr) addr.style.display = 'block'; 
}


function remove_all_items(){
    $("near").value = "";
}

function cleanUp(){
    // Clean up the HTML containers
    /*
     var record_list = document.getElementById('recordListDiv');
     while (record_list.firstChild) {
     record_list.removeChild(record_list.firstChild);
     }
     */
    //PHOADD 20080325
    Element.update('recordListDiv', '');
    $('alert1').setStyle({
        display: 'none'
    });
    
    mapviewer.removeAllOverlays();
    
    markers = new Array();
    
}

function cleanUp_routing(){

    var stepsContainer = $('routeSteps');
    while (stepsContainer.firstChild) {
        stepsContainer.removeChild(stepsContainer.firstChild);
    }
    stepsContainer.style.display = 'none';
    mapviewer.removeAllOverlays();
    
    Element.update('total_distance', multimap_dico["multimap.result.direction.total_distance"] + ' :0');
    Element.update('duration', multimap_dico["multimap.result.direction.duration"] + ' :0');
    /*	total_distance=0;
    
     
    
     route.distance.km=0;
    
     
    
     //route.distance.miles;*/
    
}

function displayStages(route){
    var curr_step = 1;
    var stages = route.stages;
    var container = $('routeSteps');
    
    /* var h2 = document.createElement('h2');
     h2.appendChild(document.createTextNode('Travel directions'));
     container.appendChild(h2);*/
    var summary = '';
    // Show the total route distance in miles:
    /*summary += '<br />Total Distance: ' + route.distance.miles + ' mile(s)';*/
    // Show the total duration of trip. Note that we display the days, hours, and minutes by
    // accessing each property: 
    
    if (route.duration.days > 0) {
        summary += route.duration.days + ' day(s) ';
    }
    if (route.duration.hours > 0) {
        summary += route.duration.hours + ' hour(s) ';
    }
    if (route.duration.minutes > 0) {
        summary += route.duration.minutes + ' minute(s) ';
    }
    var p = document.createElement('p');
    /*  p.innerHTML = summary;*/
    container.appendChild(p);
    
    Element.update('total_distance', 'Total distance: ' + route.distance.km + 'kms');
    Element.update('duration', 'est.duration: ' + summary);
    
    // The route will be returned in stages. Each stage goes from one specified 'location' to the next:
    for (var count = 0; count < stages.length; count++) {
        // Show some summary information about each stage:
        /* var stage_summary = '';
         stage_summary += '<strong>Stage ' + (count + 1) + '<' + '/strong>';
         // Show the stage distance, in miles:
         stage_summary += '<br />Stage Distance: ' + stages[count].distance.miles + ' mile(s)';
         // Show the stage duration, in days, hours and minutes:
         stage_summary += '<br />Estimated Stage Time: ';
         if (stages[count].duration.days > 0) { stage_summary += stages[count].duration.days + ' day(s) '; }
         if (stages[count].duration.hours > 0) { stage_summary += stages[count].duration.hours + ' hour(s) '; }
         if (stages[count].duration.minutes > 0) { stage_summary += stages[count].duration.minutes + ' minute(s) '; }
         var p = document.createElement('p');
         p.innerHTML = stage_summary;
         container.appendChild(p);*/
		 
        var ul = document.createElement('ul');
        ul.id = 'stage_' + count;
        ul.start = curr_step;
        
        var steps = stages[count].steps;
        
        // Now we will display each step instruction within this stage:
        
        for (var stepCount = 0; stepCount < steps.length; stepCount++) {
        
            var steps_max = steps.length - 1;
            // Label the current marker with the step number:
            var text = curr_step;
            // Make the higher numbered step markers appear 'on top of' lower ones:
            var zindex = max_zindex - curr_step + 1;
            
            // Use 'S' as marker text if this is the first step of the entire route:
            if (count == 0 && stepCount == 0) {
                text = 'S';
            }
            // Use 'F' as marker text if this is the last step of the entire route:      
            if (count == stages.length - 1 && stepCount == steps.length - 1) {
                text = 'F';
                zindex = max_zindex;
            }
            // Create a written 'instruction' using the roadname and/ or roadnumber:
            var instruction = steps[stepCount].instruction;
            var roadname = steps[stepCount].road_name;
            var roadnumber = steps[stepCount].road_number;
            
            if (roadname && roadnumber) {
                instruction += ' ' + roadname + ' (' + roadnumber + ') ';
            }
            else 
                if (roadname) {
                    instruction += ' ' + roadname + ' ';
                }
                else 
                    if (roadnumber) {
                        instruction += ' ' + roadnumber + ' ';
                    }
            
            // Show the distance of this particular step:
            var distance = '';
            if (steps[stepCount].distance.km > 0) {
                distance += steps[stepCount].distance.km + ' km(s) ';
            }
            if (distance != '') {
                distance = ' - ' + distance
            };
            
            //show the arrow of a particular step
            var arrow = '';
            if (steps[stepCount].turn_direction != 'null') 
                arrow += steps[stepCount].turn_direction;
            else 
                steps[stepCount].turn_direction = "N";
            if (stepCount != steps_max) {
            
                if (arrow != "null") {
                    arrow += '.gif';
                    arrow_img = '<img src="/resources/styles/24_WhereToBuy/images/' + arrow + '" alt="" />';
                }
                if (stepCount == 0) {
                    arrow_img = arrow_img = '<img src="/resources/styles/24_WhereToBuy/images/depart.gif" alt="" />';
                }
                else 
                    if (arrow == "null") 
                        arrow_img = arrow_img = '<img src="/resources/styles/24_WhereToBuy/images/n.gif" alt="" />';
            }
            if (stepCount == steps_max) {
                arrow_img = arrow_img = '<img src="/resources/styles/24_WhereToBuy/images/end.gif" alt="" />';
            }
            var li = document.createElement('li');
            num = stepCount + 1;
            li.innerHTML = '<div class="num2">' + (num) + '</div><div class="instructions">' + instruction + distance + '</div>' + arrow_img;
            ul.appendChild(li);
            
            // Create the step marker, using the instruction and marker text we previously created:
            createStepMarker(steps[stepCount].start_point, instruction, text, zindex);
            
            ++curr_step;
        }
        container.appendChild(ul);
    }
    
    container.style.display = 'block';
    
    // Add copyright and disclaimer, as required:
    /* var copyright = '';
    
     
    
     if (route.copyright) {copyright += 'Copyright: ' + route.copyright; }
    
     
    
     if (route.disclaimer)  {copyright += '<br />Disclaimer:  <a href="' + route.disclaimer +'">' + route.disclaimer +'<' + '/a>'; }
    
     
    
     var p = document.createElement('p');
    
     
    
     p.innerHTML = copyright;
    
     
    
     container.appendChild(p);*/
    
}

function createStepMarker(location, instruction, text, zindex){
    var marker = mapviewer.createMarker(location, {
        zIndex: zindex,
        'text': text
    });
    marker.setInfoBoxContent('<p>' + instruction + '<' + '/p>');
}

function removeAllWidgets(){
    // Remove Widgets:
    mapviewer.removeWidget(pan_zoom_widget);
    mapviewer.removeWidget(small_pan_zoom_widget);
    mapviewer.removeWidget(small_zoom_widget);
    mapviewer.removeWidget(map_type_widget);
    mapviewer.removeWidget(location_widget);
    mapviewer.removeWidget(overview_widget);
    mapviewer.removeWidget(tools_widget);
    mapviewer.removeWidget(local_info_widget);
    mapviewer.removeWidget(weather_widget);
    mapviewer.removeAllOverlays();
}

/*function print(){

    var temp = opener.document;
    Element.extend(temp);
    
    var map = opener.$("showing").innerHTML;
    
    map.toString();
    
}*/

/*
 * Added by THD 20080310
 */

function mm_so_radio_handler(id,data) {
	var element = $(id);
	var field_id = $F(element);
	for (var id in data) {
		var element = $(data[id]); 
		if (element != null) { 
			element.style.display = "none";
		}
	}
	var shown_element = $(data[field_id]);
	if (shown_element != null) { 
		shown_element.style.display = "";
		if (shown_element.onchange) {
			shown_element.onchange();
		}
	}
	return true;
}

function mm_so_select_handler(id,data) {
	var element = $(id);
	var field_id = $F(element);
	for (var id in data) {
		var element = $(data[id]);
		if (element != null) { 
			element.style.display = "none";
		}
	}
	var shown_element = $(data[field_id]); 
	if (shown_element != null) { 
		shown_element.style.display = "";
		if (shown_element.onchange) {
			shown_element.onchange();
		}
	}
	return true;
}

function mm_so_ancestor_displayed(element) {
	element = $(element);
	if (element == null) {
		return false;
	}
	if (element.style.display == "none") {
		return false;
	}
	var parent = element;
	do {
		parent = parent.parentNode;
		if (parent != null && parent.id == "div_mm_search_limits") {
			return true;
		}
		if (parent != null && parent.style.display == "none") {
			return false;
		}
	} while (parent != null);
	return true;
}

function mm_so_get_custom_fields() {
	var custom_fields = new Array();
	var custom_fields_elements = $("div_mm_search_limits").select(".mm_so_custom_field");
	//var custom_fields_elements = $$(".mm_so_custom_field");
	if (custom_fields_elements) {
		custom_fields_elements.each(function(custom_field_element) {
			if (mm_so_ancestor_displayed(custom_field_element)) {
				var field = $F(custom_field_element);
				if (field != null && field != '') {
					custom_fields.push(field);
				}
			}
		});
	}
	return custom_fields;
}



MMAttachEvent(window, 'load', onLoad);
//]]> 
// -->
//]]> 
// -->

